字典
#映射关系,字典用{}表示,字典不是列表,字典属于映射类型
#字典有两个关键字,一个是key(键),另一个是value(值)
#字典中的键,值组合称为象
1.映射
例如:
brand = [‘李宁’, ‘nike’, ‘addise’, ‘fishc’]
slogan = [‘一切皆有可能’, ‘just do it’, ‘impossible is nothing’, ‘please demo change the world’]
print(‘fishc slogan:’, slogan[brand.index(‘fishc’)])
fishc slogan: please demo change the world
2.创建字典
#字典的创建用{},元素间的映射关系用:间隔开
dict1 = {‘李宁’:‘一切皆有可能’, ‘nike’:‘just do it’, ‘addise’:‘impossible is nothing’, ‘fishc’: ‘please demo change the world’} #其中,’李宁‘称为键,’一切皆有可能‘成为值
print(‘fishc slogan is:’, dict1[‘fishc’])
fishc slogan is: please demo change the world
#另一种字典创建,利用dict()内置函数进行创建
dict4 = dict(小明 = ‘考了100分’, 小红 = ‘考了90分’)
dict4
{‘小明’: ‘考了100分’, ‘小红’: ‘考了90分’}
#如果索引的字典值不存在与字典中时,索引的值将会在该字典中创建/替换
dict4 = dict(小明 = ‘考了100分’, 小红 = ‘考了90分’)
dict4
{‘小明’: ‘考了100分’, ‘小红’: ‘考了90分’}
dict4[‘小兰’] = ‘考了50分’
dict4
{‘小明’: ‘考了100分’, ‘小红’: ‘考了90分’, ‘小兰’: ‘考了50分’}
3.字典的访问
#普通的访问字典的方法
dict2 = {1:‘one’, 2:‘two’, 3:‘three’}
dict2[2]
‘two’
#其他访问方法
1.keys() #返回字典键的引用,一般与for连用
例如:
dict1 = dict1.fromkeys(range(32), ‘赞’)
dict1
{0: ‘赞’, 1: ‘赞’, 2: ‘赞’, 3: ‘赞’, 4: ‘赞’, 5: ‘赞’, 6: ‘赞’, 7: ‘赞’, 8: ‘赞’, 9: ‘赞’, 10: ‘赞’, 11: ‘赞’, 12: ‘赞’, 13: ‘赞’, 14: ‘赞’, 15: ‘赞’, 16: ‘赞’, 17: ‘赞’, 18: ‘赞’, 19: ‘赞’, 20: ‘赞’, 21: ‘赞’, 22: ‘赞’, 23: ‘赞’, 24: ‘赞’, 25: ‘赞’, 26: ‘赞’, 27: ‘赞’, 28: ‘赞’, 29: ‘赞’, 30: ‘赞’, 31: ‘赞’}
for eachkeys in dict1.keys():
print(eachkeys)
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
2.values()
例如:
for eachkeys in dict1.values():
print(eachkeys)
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
赞
3.items() #返回字典项的引用
例如:
for eachkeys in dict1.items():
print(eachkeys)
(0, ‘赞’)
(1, ‘赞’)
(2, ‘赞’)
(3, ‘赞’)
(4, ‘赞’)
(5, ‘赞’)
(6, ‘赞’)
(7, ‘赞’)
(8, ‘赞’)
(9, ‘赞’)
(10, ‘赞’)
(11, ‘赞’)
(12, ‘赞’)
(13, ‘赞’)
(14, ‘赞’)
(15, ‘赞’)
(16, ‘赞’)
(17, ‘赞’)
(18, ‘赞’)
(19, ‘赞’)
(20, ‘赞’)
(21, ‘赞’)
(22, ‘赞’)
(23, ‘赞’)
(24, ‘赞’)
(25, ‘赞’)
(26, ‘赞’)
(27, ‘赞’)
(28, ‘赞’)
(29, ‘赞’)
(30, ‘赞’)
(31, ‘赞’)
4.字典的内建方法
1.fromkeys()
例如:
dict1 = {}
dict1.fromkeys((1, 2, 3)) #当只设置fromkeys()第一个且参数索引的值在字典中不存在时,则返回none
{1: None, 2: None, 3: None}
dict1.fromkeys((1, 2, 3), (‘one’, ‘two’, ‘three’)) #当设置两个参数时,第二个参数就作为value与第一个参数对应
{1: (‘one’, ‘two’, ‘three’), 2: (‘one’, ‘two’, ‘three’), 3: (‘one’, ‘two’, ‘three’)}
2.clear() #内置方法,清空字典
3.copy() #内置方法,浅拷贝,对对象的表面进行拷贝,与直接赋值不同
4.pop() #内置方法,给定键弹出对应的值,弹出字典中最后一个数据
5.popitem() #内置方法,弹出一个像,随机从字典中弹出一个数据
6.setdefault() #内置方法, 在字典中找不到对应的键时,自动添加,类似于get(),有两个参数(键,值)
7.update() #内置方法,利用一个字典或映射关系去更新另外一个字典