字典
思维导图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-dtIX5icv-1596381590275)(C:\Users\13242\AppData\Roaming\Typora\typora-user-images\image-20200802174637980.png)]
常见用法
可变类型和不可变类型
1.id(x)
i =1
print(id(i))
i +=2
print(id(i))
"""
94305011055840
94305011055904
"""
2.hash(x)
print(hash("Name"))
# -5745085876164239573
print(hash(('1','2','Python')))
# 8828437878820245085
print(hash(['1','2','Python']))
# TypeError: unhashable type: 'list'
print(hash({
'1','2','3'}))
# TypeError: unhashable type: 'set'
数值、字符和元组都能被哈希,因此它们是不可变类型。
列表、集合、字典不能被哈希,因此它是可变类型。
键值对
brand = ['李宁','耐克', '阿迪达斯']
slogan = ['- 切皆有可能','Just do it','Impossible is nothing']
print("耐克的口号是",slogan[brand.index('耐克')])
dic ={
'LiNing':'Everything is possible','Nick':'Just do it','Adam':'Impossible is nothing'}
print('Nick\'s goal is ',dic['Nick'])
# 耐克的口号是 Just do it
# Nick's goal is Just do it
创建和访问字典
dict1 ={
1:'one',2:'two',3;'three'}
print(dict1)
print(dict1[1])
print(dict1[4])
# {1: 'one', 2: 'two', 3: 'three'}
# one
# KeyError: 4
dic2 ={
'rice':35,'wheat':101,'corn':67}
print(dic2) # {'rice':35,'wheat':101,'corn':67}
print(dic2['rice']) # 35
- dict.fromkeys(seq[,value])