a =dict(one=1, two=2, three=3)
b ={'one':1,'two':2,'three':3}
c =dict(zip(['one','two','three'],[1,2,3]))
d =dict([('two',2),('one',1),('three',3)])
e =dict({'three':3,'one':1,'two':2})
f =dict({'one':1,'three':3}, two=2)print(a == b == c == d == e == f)
字典的操作
1、 list(d) 返回字典 d 中使用的所有键的列表。
a =dict(one=1, two=2, three=3)print(list(a))['one','two','three']
2、 len(d)返回字典 d 中的项数。
a =dict(one=1, two=2, three=3)print(len(a))3
3、 d[key]返回 d 中以 key 为键的项。 如果映射中不存在 key 则会引发 KeyError。
a =dict(one=1, two=2, three=3)print(a["two"])2print(a["twoo"])
KeyError:'twoo'
4、 d[key]=value将 d[key] 设为 value。
d ={'one':1,'two':2,'three':3}print(d['one'])1
d['one']=10print(d['one'])10
5、 del d[key]将 d[key] 从 d 中移除。如果映射中不存在 key 则会引发 KeyError。
d ={'one':1,'two':2,'three':3}print(d)del d['one']print(d){'two':2,'one':10,'three':3}{'two':2,'three':3}del d['onee']
KeyError:'onee'
6、 key in d 如果 d 中存在键 key 则返回 True,否则返回 False。
d ={'one':1,'two':2,'three':3}print('one'in d)print('five'in d)TrueFalse
7、 keynotind等价于 not key in d。
d ={'one':1,'two':2,'three':3}print('five'notin d)print('one'notin d)TrueFalse
d ={'one':1,'two':2,'three':3}print(d.setdefault('one'))print(d.setdefault('onee'))print(d.setdefault('onee'),100)1NoneNone100
19、 update([other])使用来自 other 的键/值对更新字典,覆盖原有的键。 返回 None。
d ={'one':1,'two':2,'three':3}
d1 ={'one':10,'name':'jason'}
d.update(d1)print(d){'one':10,'two':2,'three':3,'name':'jason'}
20、 values() 返回由字典值组成的一个新视图。
d ={'one':1,'two':2,'three':3}print(d.values())
dict_values([1,2,3])for i in d.values():print(i)123
21、 d|other 合并 d 和 other 中的键和值来创建一个新的字典,两者必须都是字典。当 d 和 other 有相同键时, other 的值优先。
d ={'one':1,'two':2,'three':3}
d1 ={'one':10,'two':20,'three':30}print(d | d1){'one':10,'two':20,'three':30}
d ={'one':1,'two':2,'three':3}
d1 ={'name':'jason','age':18}print(d | d1){'one':1,'two':2,'three':3,'name':'jason','age':18}
22、 d|=other 用 other 的键和值更新字典 d ,other 可以是 mapping 或 iterable 的键值对。当 d 和 other 有相同键时, other 的值优先。
d ={'one':1,'two':2,'three':3}
d1 ={'name':'jason','age':18}
d |= d1
print(d){'one':1,'two':2,'three':3,'name':'jason','age':18}
d ={'one':1,'two':2,'three':3}
d1 ={'one':10,'two':20,'three':30}
d |= d1
print(d){'one':10,'two':20,'three':30}# mapping# iterable1={'name':'jason','age':18}
d |= d1
print(d){'one':1,'two':2,'three':3,'name':'jason','age':18}
d ={'one':1,'two':2,'three':3}
d1 ={'one':10,'two':20,'three':30}
d |= d1
print(d){'one':10,'two':20,'three':30}# mapping# iterable