字典的一种内建方法:
dict1.fromkeys(),用于创建并返回一个新的字典
>>> dict1 = {}
>>> dict1.fromkeys((1,2,3))
{1: None, 2: None, 3: None}
>>> dict2 = {}
>>> dict2.fromkeys((1,2,3),"Number")
{1: 'Number', 2: 'Number', 3: 'Number'}
>>> dict3 = {}
>>> dict3.fromkeys((1,2,3), ("one","two","three"))
{1: ('one', 'two', 'three'), 2: ('one', 'two', 'three'), 3: ('one', 'two', 'three')}
访问字典的方法:
1)dict1.keys() 返回键
2) dict1.value() 返回值
3)dict1.items() 返回键值对(也就是项)
4)dict1.get() 对应键的值不存在的话返回一个None,这样程序就不会报错
5)key in dict1 查找的是键,而不是值
6)dict1.clear() 清空字典,不建议使用直接赋空值的方法:dict1 = {}
7)dict1.copy():浅拷贝(见练习题5)
8)dict1.pop():给定键弹出相应值
9)dict1.popitem():给定键弹出相应项(包括键和值)
10)dict1.setdefault():找不到给定键对应的值话会自动在字典中创建一个基于该键的项(区别于dict1.get()的结果)
11)dict1.update():根据一个字典或映射关系去更新另一个字典
链接:https://www.jianshu.com/p/748d282fc1e4
来源:简书