字典是另一种可变容器模型,且可存储任意类型对象。
字典的每个键值(key->value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:
a = {key1 : value1, key2 : value2 }
a = {'hesor': 10, 20: 'chen'}
print(a['hesor'], a[20])
'''
Output:
10 chen
'''
a = {'hesor': 10, 20: 'chen'}
a['hesorchen'] = 30 # 新增键值
a['hesor'] = 40 # 修改值
print(a['hesor'], a[20], a['hesorchen'])
'''
Output:
40 chen 30
'''
a = {'hesor': 10, 20: 'chen'}
del a['hesor'] # 删除键
del a # 删除字典
a.clear() # 清空字典
len(dict)
:返回键的数量
len(dict)
:返回键的数量
dict.clear()
:清空字典
dict.copy()
:返回字典的浅复制字典
dict.fromkeys(seq,val)
:创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值,见示例5
dict.get(key)
:如果key是字典中的键,返回值,否则返回None,见示例6
key in dict
:返回True或False
dict.kyes()
:返回一个迭代器,可以用list()转化为列表,见示例7
dict.items()
:返回一个迭代器,可以用list()转化为列表,见示例8
dict.values()
:返回一个迭代器,可以用list()转化为列表,见示例9
dict1.update(dict2)
:以dict2更新dict1,遵循字典的修改规则,见示例10
dict.pop(key)
:删除字典中的键key,并且返回这个键对应的值
a = {10: 'chen'}
b = a.fromkeys((1, 2, 3, 4, 9), 'like')
print(a, '\n', b)
'''
Output:
{10: 'chen'}
{1: 'like', 2: 'like', 3: 'like', 4: 'like', 9: 'like'}
'''
a = {10: 'chen'}
print(a.get(10))
print(a[10])
print(a.get(11)) # 输出None
print(a[11]) # 报错
a = {1: 'hesorchen', 2: 'qwq', 3: 'T_T'}
for k in a.keys():
print(k, a[k])
'''
Output:
1 hesorchen
2 qwq
3 T_T
'''
a = {1: 'hesorchen', 2: 'qwq', 3: 'T_T'}
for Item in a.items():
print(Item)
'''
Output:
(1, 'hesorchen')
(2, 'qwq')
(3, 'T_T')
'''
a = {1: 'hesorchen', 2: 'qwq', 3: 'T_T'}
for val in a.values():
print(val)
'''
Output:
hesorchen
qwq
T_T
'''
a = {1: 'hesorchen', 2: 'qwq', 3: 'T_T'}
b = {1: 'orz', 4: 'O.O', 5: 'qaq'}
a.update(b)
print(a) # a原来的键1的值被覆盖
'''
Output:
{1: 'orz', 2: 'qwq', 3: 'T_T', 4: 'O.O', 5: 'qaq'}
'''
a = {1: 'hesorchen', 2: 'qwq', 3: 'T_T'}
print(a.pop(1)) # a原来的键1的值被覆盖
print(a)
'''
Output:
hesorchen
{2: 'qwq', 3: 'T_T'}
'''