字典生成式
1.通过关键字dict和关键字参数创建 >>> dic = dict(spam = 1, egg = 2, bar =3) >>> dic {'bar': 3, 'egg': 2, 'spam': 1}
2.通过二元组列表创建 >>> list = [('spam', 1), ('egg', 2), ('bar', 3)] >>> dic = dict(list) >>> dic {'bar': 3, 'egg': 2, 'spam': 1}
3.dict和zip结合创建 >>> dic = dict(zip('abc', [1, 2, 3])) >>> dic {'a': 1, 'c': 3, 'b': 2}
4.通过字典推导式创建 >>> dic = {i:2*i for i in range(3)} >>> dic {0: 0, 1: 2, 2: 4}
5.通过dict.fromkeys()创建 通常用来初始化字典, 设置value的默认值
>>>lst=["a","b","c","d"]
>>> dic = dict.fromkeys(lst[o], "x")
>>> dic {a:"x"}
6.for循环遍历列表,将列表中小元组的key和value取出,作为字典的key:value
>>>list4=[('name','zhagnsan'),('age',22),('phone',110)]
>>>dict_1={key:value for key,value in list4}
>>>print(dict_1)
{'name': 'zhagnsan', 'age': 22, 'phone': 110}
7.其他 >>> list = ['x', 1, 'y', 2, 'z', 3] >>> dic = dict(zip(list[::2], list[1::2])) >>> dic {'y': 2, 'x': 1, 'z': 3}
8.update()用法
描述
Python 字典(Dictionary) update() 函数把字典dict2的键/值对更新到dict里
语法
update()方法语法:
dict.update(dict2)
参数
- dict2 -- 添加到指定字典dict里的字典。
- 参数说明参数说明
将e中键-值对添加到字典d中,e可能是字典,也可能是键-值对序列。
返回值
该方法没有任何返回值。
实例
以下实例展示了 update()函数的使用方法:
dict = {'Name': 'Zara', 'Age': 7} dict2 = {'Sex': 'female' } dict.update(dict2) print "Value : %s" % dict
以上实例输出结果为:
Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}
详细实例d = {‘one’:1,’two’:2}
d.update({‘three’:3,’four’:4}) # 传一个字典 print(d)
#{‘one’: 1, ‘four’: 4, ‘three’: 3, ‘two’: 2}
d.update(five=5,six=6) # 传关键字 print(d) #{‘one’: 1, ‘four’: 4, ‘three’: 3, ‘five’: 5, ‘two’: 2, ‘six’: 6}
d.update([(‘seven’,7),(‘eight’,8)]) # 传一个包含一个或多个元组的列表 print(d)
#{‘seven’: 7, ‘one’: 1, ‘four’: 4, ‘three’: 3, ‘five’: 5, ‘two’: 2, ‘six’: 6, ‘eight’: 8}
d.update(([‘nice’,9],[‘ten’,10])) # 传一个包含一个或多个列表的元组 print(d) #{‘seven’: 7, ‘one’: 1, ‘four’: 4, ‘three’: 3, ‘ten’: 10, ‘five’: 5, ‘nice’: 9, ‘two’: 2, ‘six’: 6, ‘eight’: 8}
d.update(zip([‘eleven’,’twelve’],[11,12])) # 传一个zip()函数 print(d) #
{‘one’: 1, ‘four’: 4, ‘three’: 3, ‘twelve’: 12, ‘ten’: 10, ‘seven’: 7, ‘six’: 6, ‘eleven’: 11, ‘two’: 2, ‘nice’: 9, ‘five’: 5, ‘eight’: 8}
d.update(one=111,two=222) # 使用以上任意方法修改存在的键对应的值 print(d)
#
{‘one’: 111, ‘four’: 4, ‘three’: 3, ‘twelve’: 12, ‘ten’: 10, ‘seven’: 7, ‘six’: 6, ‘eleven’: 11, ‘two’: 222, ‘nice’: 9, ‘five’: 5, ‘eight’: 8}
以上实例输出结果为: {‘one’: 1, ‘four’: 4, ‘three’: 3, ‘two’: 2} {‘one’: 1, ‘four’: 4, ‘three’: 3, ‘five’: 5, ‘two’: 2, ‘six’: 6} {‘seven’: 7, ‘one’: 1, ‘four’: 4, ‘three’: 3, ‘five’: 5, ‘two’: 2, ‘six’: 6, ‘eight’: 8} {‘seven’: 7, ‘one’: 1, ‘four’: 4, ‘three’: 3, ‘ten’: 10, ‘five’: 5, ‘nice’: 9, ‘two’: 2, ‘six’: 6, ‘eight’: 8} {‘one’: 1, ‘four’: 4, ‘three’: 3, ‘twelve’: 12, ‘ten’: 10, ‘seven’: 7, ‘six’: 6, ‘eleven’: 11, ‘two’: 2, ‘nice’: 9, ‘five’: 5, ‘eight’: 8} {‘one’: 111, ‘four’: 4, ‘three’: 3, ‘twelve’: 12, ‘ten’: 10, ‘seven’: 7, ‘six’: 6, ‘eleven’: 11, ‘two’: 222, ‘nice’: 9, ‘five’: 5, ‘eight’: 8}
dict ={'Name':'Zara','Age':7} dict2 ={'Sex':'female'} dict.update(dict2)print"Value : %s"% dict