Python中的dict
dict_lst = [
('字典的键必须可哈希',),
('字典的键重复覆盖',),
('字典可迭代')
('增',),
('删',),
('改',),
('查',),
('练习',),
]
字典的键必须可哈希
(ps: key-value查询效率高)
>>>dic = {[0]: 1}
typeerror: unhashable type: 'list'
字典的键重复覆盖
>>>dic = {'k': 1, 'k': 2, 'k': 3}
>>>dic
{'k': 3}
字典可迭代
>>>from collections import iterable
>>>isinstance(dict(), iterable)
true
增
>>>dic = {'k1': 1, 'k2': 2}
>>>dic['k3'] = [3, 4]
>>>dic
{'k1': 1, 'k2': 2, 'k3': [3, 4]}
>>>dic = {'k1': 1, 'k2': 2}
>>>'key existed' if 'k3' in dic else dic.setdefault('k3', 4)
4
>>>dic
{'k1': 1, 'k2': 2, 'k3': 4}
删
>>>dic = {'k1': 1, 'k2': 2, 'k3': 3}
>>>dic.pop('k1')
1
>>>dic
{'k2': 2, 'k3': 3}
>>>dic = {'k1': 1, 'k2': 2, 'k3': 3}
>>>dic.popitem()
('k3', 3)
>>>dic
{'k1': 1, 'k2': 2}
>>>dic.clear()
>>>dic
{}
>>>del dic
>>>dic
nameerror: name 'dic' is not defined
改
>>>dic = {'k1': 1, 'k2': 2}
>>>dic['k1'] = 4
>>>dic
{'k1': 4, 'k2': 2}
>>>dic_1 = {'k1': 1, 'k2': 2}
>>>dic_2 = {'k3': 3}
>>>dic_2.update(dic_1)
>>>dic_2
{'k3': 3, 'k1': 1, 'k2': 2}
查
>>>dic = {'name': 'hopen', 'age': 1}
>>>for key in dic:
... key, dic[key]
...
('name', 'hopen')
('age', 1)
练习
更改字典的键
>>>dic = {'k1': 1, 'k2': 2}
>>>dic['k4'] = dic.pop('k1')
>>>dic
{'k2': 2, 'k4': 1}
上一篇: 儿子爆笑表述
下一篇: python--线程同步原语