作者博文地址:https://www.cnblogs.com/liu-shuai/
字典是Python语言中唯一的映射类型。字典对象是可变的,它是一个容器类型,支持异构、任意嵌套。
创建字典
语法:{key1:val1,key2:val2,.....}
dict1 = {} #创建空字典
dict2 = {'n1':'liush','n2':'spirit','n3':'tester'}
使用函数dict创建字典
1 >>>D = dict(name='spititman',age=28,gender='M')
2 >>>print D
3 {'gender': 'M', 'age': 28, 'name': 'spititman'}
使用zip和dict创建字典
1 zip语法:
2 zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
3 实例展示:
4 >>>L = zip('xyz','123')
5 >>>print L
6 [('x', '1'), ('y', '2'), ('z', '3')]
7
8 >>>L = zip('xyz','123','abc')
9 >>>print L
10 [('x', '1', 'a'), ('y', '2', 'b'), ('z', '3', 'c')]
11 ################################################################################
12 >>>D = dict(zip('xyz','123'))
13 >>>print D
14 {'y': '2', 'x': '1', 'z': '3'}
15
16 >>>D = dict(zip('xyz','123','abc'))
17 >>>print D
18 ValueError: dictionary update sequence element #0 has length 3; 2 is required
字典常用操作及实例展示
可以使用dir(dict)查看字典支持的操作方法
clear
功能:清空字典所有元素
语法:D.clear() -> None. Remove all items from D
实例展示:
1 >>>D = {'n1':'liush','n2':'spirit','n3':'tester'}
2 >>>D.clear()
3 >>>print D
4 {}
copy
功能:浅复制字典。
语法:D.copy() -> a shallow copy of D
实例展示:
1 >>>D = {'n1':'liush','n2':'spirit','n3':'tester'}
2 >>>id(D)
3 140388211911208
4 >>>D1 = D.copy()
5 >>>print D1
6 {'n1': 'liush', 'n2': 'spirit', 'n3': 'tester'}
7 >>>id(D1)
8 140388110074776
fromkeys
功能:用于创建一个新字典,以序列S中的元素作为字典的键,v为新字典中所有键对应的初始值,默认为none。
语法:dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.v defaults to None
实例展示:
1 >>>L = ['spirit','man','liush']
2 >>>D_L = dict.fromkeys(L)
3 >>>print D_L
4 {'liush': None, 'spirit': None, 'man': None}
5 ########################################################
6 >>>D_L = dict.fromkeys(L,'test')
7 >>>print D_L
8 {'liush': 'test', 'spirit': 'test', 'man': 'test'}
get
功能:获取指定键的值
语法:D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None
实例展示:
1 >>>D = {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}
2 >>>D1 = D.get('n4')
3 >>>print D1
4 none #n4不在字典D中,返回默认值none
5 ##########################################################
6 >>>D2 = D.get('n4','check')
7 >>>print D2
8 check #n4不在字典D中,返回指定值check
9 ##########################################################
10 >>>D3 = D.get('n2')
11 >>>print D3
12 spirit #n2在字典D中,返回n2对应的值
13 ##########################################################
14 >>>D4 = D.get('n2','check')
15 >>>print D4
16 spirit #n2在字典D中,指定值无效,依然返回其对应值
has_key
功能:判断字典中是否存在指定键
语法:D.has_key(k) -> True if D has a key k, else False
实例展示:
1 >>>D = {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}
2 >>>D.has_key('n4')
3 False
4 ######################################################
5 >>>D.has_key('n2')
6 True
items
功能:返回以字典中的键值对组成的元组作为元素的列表
语法:D.items() -> list of D's (key, value) pairs, as 2-tuples
实例展示:
1 >>>D = {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}
2 >>>L = D.items()
3 >>>print L
4 [('n1', 'liushuai'), ('n2', 'spirit'), ('n3', 'tester')]
5 >>>type(L)
6 <type 'list'>
iteritems
功能:对以字典中的键值对组成的元组进行迭代,可用于for循环
语法:D.iteritems() -> an iterator over the (key, value) items of D
实例展示:
1 >>>D = {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}
2 >>>L = D.iteritems()
3 >>>print L
4 <dictionary-itemiterator object at 0x7faea6c97158> #生成一个迭代器地址
5 >>>L.next() #开始迭代
6 ('n1', 'liushuai')
7 >>>L.next()
8 ('n2', 'spirit')
9 >>>L.next()
10 ('n3', 'tester')
11 >>>L.next() #迭代完成后报错
12 Traceback (most recent call last):
13 File "<stdin>", line 1, in <module>
14 StopIteration
15 #########################################################################
16 >>>for i in D.iteritems(): #使用for循环遍历
17 ... print i
18 ...
19 ('n1', 'liushuai')
20 ('n2', 'spirit')
21 ('n3', 'tester')
iterkeys
功能:对字典中的键进行迭代(遍历)
语法:D.iterkeys() -> an iterator over the keys of D
实例展示:
1 >>>D = {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}
2 >>>L = D.itervalues()
3 >>>print L
4 <dictionary-keyiterator object at 0x7faea6c971b0>
5 >>>L.next()
6 'n1'
7 >>>L.next()
8 'n2'
9 >>>L.next()
10 'n3'
11 >>>L.next()
12 Traceback (most recent call last):
13 File "<stdin>", line 1, in <module>
14 StopIteration
15 #############################################################
16 >>>for i in D.iterkeys():
17 ... print i
18 ...
19 n1
20 n2
21 n3
itervalues
功能:对字典中的键进行迭代(遍历)
语法:D.itervalues() -> an iterator over the values of D
实例展示:
1 >>>D = {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}
2 >>>L = D.itervalues()
3 >>>print L
4 <dictionary-valueiterator object at 0x7faea6c97208>
5 >>>L.next()
6 'liushuai'
7 >>>L.next()
8 'spirit'
9 >>>L.next()
10 'tester'
11 >>>L.next()
12 Traceback (most recent call last):
13 File "<stdin>", line 1, in <module>
14 StopIteration
15 #############################################################
16 >>>for i in D.itervalues():
17 ... print i
18 ...
19 liushuai
20 spirit
21 tester
keys
功能:以列表的形式返回所有键
语法:D.keys() -> list of D's keys
实例展示:
1 >>>D = {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}
2 >>>L = D.keys()
3 >>>print L
4 ['n1','n2','n3']
pop
功能:从字典中删除指定的键,返回其对应的值。
语法:D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised
实例展示:
1 >>>D = {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}
2 >>>D.pop('n4') #指定的键不存在,返回报错
3 Traceback (most recent call last):
4 File "<stdin>", line 1, in <module>
5 ##################################################
6 KeyError: 'n4' #指定的键不存在,返回指定的值
7 >>>D.pop('n4','check')
8 'check'
9 ##################################################
10 >>>D.pop('n2') #指定的键存在,返回其对应值
11 'spirit'
12 ##################################################
13 >>>D.pop('n3','check') #指定的键存在,指定值无效,依然返回其对应值
14 'tester'
15 ##################################################
popitem
功能:随机删除字典的键值对并以元组的形式返回
语法:D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
实例展示:
1 >>>D = {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}
2 >>>D.popitem()
3 ('n1', 'liushuai')
4 >>>D.popitem()
5 ('n2', 'spirit')
6 >>>D.popitem()
7 ('n3', 'tester')
8 >>>D.popitem() #当字典为空时,抛出异常。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'popitem(): dictionary is empty'
setdefault
功能:查找键值。若键不在字典中,将会添加键并将值设定为默认值
语法:D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
实例展示:
1 >>>D = {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}
2 ##指定的键存在,则返回其对应的值,原字典不变
3 >>>D.setdefault('n2')
4 'spirit'
5 >>>print D
6 {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}
7 #######################################################################
8 ##指定的键不存在,则修改原字典,该键对应的值默认为none
9 >>>D.setdefault('n4')
10 >>>print D
11 {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester', 'n4': None}
12 #######################################################################
13 ##指定的键不存在,则修改原字典,该键对应的值为指定值
14 >>>D.setdefault('n5','check')
15 >>>print D
16 {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester', 'n4': None, 'n5': 'check'}
update
功能:以字典或迭代器更新原字典
语法: D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
In either case, this is followed by: for k in F: D[k] = F[k]
实例展示:
1 >>>D = {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}
2 >>>D1 = {'n1':'liush','n4':'Jerry'}
3 >>>D2 = {1:'IT',2:'SALE'}
4 #键相同时,则其对应的原字典的值将被覆盖
5 >>>D.update(D1)
6 {'n1': 'liush', 'n2': 'spirit', 'n3': 'tester', 'n4': 'Jerry'}
7 ####################################################
8 #键不同时,则追加
9 >>>D.update(D2)
10 {1: 'IT', 2: 'SALE', 'n1': 'liush', 'n2': 'spirit', 'n3': 'tester', 'n4': 'Jerry'}
values
功能:以列表的形式返回所有值
语法:D.values() -> list of D's values
实例展示:
1 >>>D = {'n1': 'liushuai', 'n2': 'spirit', 'n3': 'tester'}
2 >>>L = D.values()
3 >>>print L
4 ['liushuai', 'spirit', 'tester']
作者博文地址:https://www.cnblogs.com/liu-shuai/