知识点思维导图
![](https://img-blog.csdnimg.cn/direct/fef6c702c6674d6f87046a4cc7a6b9cf.png)
1.字典的创建
# (1)直接使用{}创建字典
d={10:'cat',20:'dog',30:'sheep',20:'zoo'}
print(d) # key值相同时,value值进行了覆盖
# (2)使用zip创建字典
lst1=[1,2,3,4]
lst2=['cat','dog','car','sheep','zoo']
zipobj=zip(lst1,lst2)
d=dict(zipobj)
print(d)
# (3)使用参数创建字典
d=dict(cat=1,dog=2) # 左侧cat是key,右侧1是value
print(d)
# 元组可以作为字典中的键
t=(1,2,3)
print({t:10}) # key是t,value是10
# 然而列表是不可以作为字典中的键,因为列表是可变数据类型,key的值必须是不可变的
# 字典属于序列
print('max:',max(d))
print('min:',min(d))
print('len:',len(d))
{10: 'cat', 20: 'zoo', 30: 'sheep'}
{1: 'cat', 2: 'dog', 3: 'car', 4: 'sheep'}
{'cat': 1, 'dog': 2}
{(1, 2, 3): 10}
max: dog
min: cat
len: 2
2.字典的删除
# 字典的删除
del d
3.访问字典元素
d={'1':1,'2':2,'3':3}
# 访问字典中的元素
# (1)使用d[key]
print(d['1'])
# (2)使用d.get[key]
print(d.get('1'))
1
1
4.字典的遍历
# 字典的遍历,获取的是一个元组
for item in d.items():
print(item)
# 在使用for循环遍历时,分别获取key,value
for key,value in d.items():
print(key,'---->',value)
('1', 1)
('2', 2)
('3', 3)
1 ----> 1
2 ----> 2
3 ----> 3
5.字典的操作
![](https://img-blog.csdnimg.cn/direct/ad8c460e4a8d4defa88504e82d271b2f.png)
6.字典生成式
1.d={ key:value for item in range }
# 字典生成式
import random
d={item:random.randint(1,100) for item in range(4)}
print(d)
{0: 35, 1: 61, 2: 74, 3: 89}
2. d={ key:value for key,value in zip(lst1,lst2)}
# 创建两个列表
lst1=[1,2,3]
lst2=['ty','ty1','ty2']
d={key:value for key,value in zip(lst1,lst2)}
print(d)
{1: 'ty', 2: 'ty1', 3: 'ty2'}