Traceback (most recent call last):4.7.1.2 通过字典推导式创建
File "C:\Program Files\Python3102\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "", line 1, in
TypeError: unhashable type: 'list'
{0: 0, 1: 1, 2: 4}4.7.1.3 通过dict函数创建
2>>> dct['zero'] # 如果键不存在,则会报错
Traceback (most recent call last):4.7.2.2 遍历字典
File "C:\Program Files\Python3102\lib\code.py", line 90, in runcode
exec(code, self.locals)
one4.7.2.3 成员资格检查
two
three
True4.7.3 字典的修改
False
224.7.3.2 通过|得到更新后的字典
{'one': 1, 'two': 22, 'three': 3, 'zero': 0}4.7.3.3 通过|=原地更新字典
{'one': 1, 'two': 22, 'three': 3, 'zero': 0}4.7.3.4 通过解包方式得到更新后的字典
{'one': 1, 'two': 22, 'three': 3, 'zero': 0}4.7.4 字典的删除
Traceback (most recent call last):4.7.4.2 删除整个字典
File "C:\Program Files\Python3102\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "", line 1, in
KeyError: 'two'
Traceback (most recent call last):4.7.5 字典的方法
File "C:\Program Files\Python3102\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "", line 1, in
NameError: name 'dct' is not defined. Did you mean: 'dct1'?
{'one': 1, 'two': 22, 'three': 3, 'zero': 0}4.7.5.2 删除元素
{}4.7.5.2.2 pop(key[,default])
1>>> dct
{'two': 2, 'three': 3}>>> dct.pop('zero', '没有这个key')
'没有这个key'>>> dct.pop('zero')
Traceback (most recent call last):4.7.5.2.3 popitem()
File "C:\Program Files\Python3102\lib\code.py", line 90, in runcode
exec(code, self.locals)
File "", line 1, in
KeyError: 'zero'
('three', 3)>>> dct
{'one': 1, 'two': 2}4.7.5.3 查询统计类
1注意:
None
0
0>>> dct
{'one': 1, 'two': 2, 'three': 3}>>> dct.setdefault('zero', 0)
0>>> dct
{'one': 1, 'two': 2, 'three': 3, 'zero': 0}4.7.5.3.2 keys()、values()
dict_keys(['one', 'two', 'three'])4.7.5.3.3 items()
dict_items([('one', 1), ('two', 2), ('three', 3)])4.7.5.4 其它类
{'one': 1, 'two': 2, 'three': 3}4.7.5.4.2 fromkeys(seq, val)
{'a': None, 'b': None, 'c': None}4.7.6 字典的应用
{'a': 123, 'b': 123, 'c': 123}
"Cecil's phone number is 3258."在模板系统中,这种字符串格式设置方式很有用(下面的示例使用的是HTML)。
My Home Page My Home Page4.7.6.2 字典排序
Welcome to my home page!
one 14.7.6.2.2 根据value排序
three 3
two 2
zero 0
one 1
two 2
three 3
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) | Powered by Discuz! X3.4 |