1、 字典是无序的(3.7版本之前)
2、 他的存储结果是 key:value
一、遍历字典,同时遍历key,value
students = {"name":"王二","age":13}
for key,value in students.items():
print(key+":"+str(value))
输出
name:王二
age:13
二、get() 和 setdefault()的区别
get():查找字典里的key,如果找不到,返回一个默认值 get(key,default_value)
setdefault(): 查找字典里的key,找果找不到,增加这个key,并为key设置默认值, setdefault(key,default_value)
student = {"name":"张三","age":27,"score":60}
address1 = student.get("address",None)
print(student)
print(address1)
输出结果:
{'name': '张三', 'age': 27, 'score': 60} #没有改变字典结果
None #找不到address 输出默认值None
address2 = student.setdefault("address",None)
print(student)
print(address2)
输出结果:
{'name': '张三', 'age': 27, 'score': 60, 'address': None} #改变了字典结果
None #找不到address 为字典增加了key address,并设置了默认值
通过以上,我们看看 setdefault()很好用的方法
我们现在一堆学生
students = [{"name":"张三"},{"name":"李四","group":1}]
有的学生有分组,有的学生没有分组,我们要找到没有分组的学生,给他随机分个组
import random
students = [{"name":"张三"},{"name":"李四","group":1}]
group = random.randint(1,4)
for student in students:
student.setdefault("group",group)
print(students)
[{'name': '张三', 'group': 3}, {'name': '李四', 'group': 1}]
三、字典删除:pop()
如果你想删除字典里的字段,你能会这样
student = {"name":"张三","age":27,"score":60}
try:
del student["address"] #万一字典里没这字段呢,可不能报错,所以得try一下
except KeyError:
pass
有没有更简单的方式呢 pop(key,None)
student = {"name":"张三","age":27,"score":60}
student.pop("name",None) #如果有就删除
print(student)
输出结果:{'age': 27, 'score': 60}
student = {"name":"张三","age":27,"score":60}
student.pop("address",None) #如果没有也不会报异常
print(student)
输出结果:
{'name': '张三', 'age': 27, 'score': 60}
三、字典推导式
students = {"name": "王二", "age": 13,}
students = {key:value for key,value in students.items() if "二" in str(value) }
print(students)
{'name': '王二'}
四、有序字典 OrderedDict()
在python3.7以前,字典是无序的,但是如果你想判断两个字典不仅key和value一样,字典的顺序也一样时,怎么办呢
可以将OrderedDict()将字典封装成有序字典
from collections import OrderedDict
student1 ={"name": "李四", "group": 1}
student2 ={"name": "李四", "group": 1}
student3 = {"group": 1,"name": "李四"}
print(student1 == student2) #true
print(student1 == student3) #true
student1 = OrderedDict(student1)
student2 = OrderedDict(student2)
student3 = OrderedDict(student3)
print(student1 == student2) #true
print(student1 == student3) #false