Python入门(03) -- 字典
一、字典操作
1.创建字典
1)创建带有键-值对的字典
person = {'first_name': 'zhang', 'last_name': 'san'}
2)创建一个空字典
person = {}
2.访问字典的值
可以通过指定字典的键来访问字典的键的值
person = {'first_name': 'zhang', 'last_name': 'san'}
print(person['first_name'])
print(person['last_name'])
打印结果:
zhang
san
3.在字典里面添加元素
person = {'first_name': 'zhang', 'last_name': 'san'}
person['middle_name'] = 'quan'
print(person)
打印结果:
{'first_name': 'zhang', 'last_name': 'san', 'middle_name': 'quan'}
4.修改字典键里面的值
person = {'first_name': 'zhang', 'last_name': 'san'}
person['first_name'] = 'zhao'
print(person)
打印结果:
{'first_name': 'zhao', 'last_name': 'san'}
5.删除键-值对
person = {'first_name': 'zhang', 'last_name': 'san'}
del person['last_name']
print(person)
打印结果:
{'first_name': 'zhang'}
二、遍历字典
1.遍历所有的键-值对
person = {
'first_name': 'zhao',
'middle_name': 'quan',
'last_name': 'zhu'
}
for key, value in person.items():
print(key + '\t' + value)
打印结果:
first_name zhao
last_name zhu
middle_name quan
2.遍历字典中的所有键
person = {
'first_name': 'zhao',
'middle_name': 'quan',
'last_name': 'zhu'
}
for key in person.keys():
print(key)
打印结果:
first_name
last_name
middle_name
3.遍历字典中的所有值
person = {
'first_name': 'zhao',
'middle_name': 'quan',
'last_name': 'zhu'
}
for value in person.values():
print(value)
打印结果:
zhao
zhu
quan
4.按顺序遍历字典中的所有值
person = {
'first_name': 'zhao',
'middle_name': 'quan',
'last_name': 'zhu'
}
for value in sorted(person.values()):
print(value)
打印结果:
quan
zhao
zhu
三、嵌套
1.字典列表
person_1 = {'name': 'zhao', 'age': 11}
person_2 = {'name': 'qian', 'age': 17}
person_3 = {'name': 'sun', 'age': 19}
people = [person_1, person_2, person_3]
for person in people:
print(person)
打印结果:
{'age': 11, 'name': 'zhao'}
{'age': 17, 'name': 'qian'}
{'age': 19, 'name': 'sun'}
2.在字典中存储列表
person = {
'names': ['zhao', 'tie', 'zhu'],
'age': 10
}
for name in person['names']:
print(name)
print(person['age'])
打印结果:
zhao
tie
zhu
10
3.在字典中存储字典
people = {
'person_1': {'name': 'zhao', 'age': 11},
'person_2': {'name': 'qian', 'age': 17},
'person_3': {'name': 'sun', 'age': 19}
}
for person in people.values():
for key, value in person.items():
print(key + '\t' + str(value))
打印结果:
age 17
name qian
age 19
name sun
age 11
name zhao