Python07,字典
字典是一种非常有用的数据类型,就像我们上学用到的字典,通过笔画和拼音来查找对应汉字的详细解释。
Python中字典的每个元素都有对应的键(Key)和值(Value),一般称为键值对。以下的代码创建一个名为info_dict的字典,包含了四对元素。
info_dict = {
'stu101':"James",
'stu102':"Alex",
'stu103':"Paul",
'stu104':"Mark"
}
- 字典中的元素是无序的
- 字典的键必须是唯一的,不能重复,值可以重复。
- 字典中的键无法修改,而值可以修改,可以是任何对象。
字典的添加
info['stu105'] = "Lucy"
print(info)
还可以通过update()方法来添加一个或者多对元素:
info_dict.update({'stu108':"Lucy",'stu109':"Lily"})
print(info_dict)
字典的删除
info.pop('stu101')
print(info)
还可以这样删除
del info['stu102']
print(info)
还可以随机删除
info.popitem()
print(info)
字典的修改,修改不存在的key会直接变成添加
info['stu105'] = "James"
print(info)
字典的查找
print('stu102' in info) #判断key是否在字典中存在
print(info.get('stu102')) #获取某个key对应的值,不存在则返回None
字典的多级嵌套
food_catalog = {
'vegetables':{
"cabbage":[1.5,'cheap'],
"radish":[2.0,'cheap'],
"carrot":[2.5,'cheap'],
},
'fruit':{
"apple":[5.8,'cheap'],
"banana":[4.5,'cheap'],
"pear":[3.9,'cheap'],
},
'meats':{
"pork":[16,'expensive'],
"mutton":[28,'expensive'],
"beef":[48,'expensive'],
},
'drinks':{
"yogourt":[8,'expensive'],
"tea":[5,'cheap'],
"cola":[4,'cheap'],
}
}
food_catalog['drinks']["yogourt"][1] += ',not really'
print(food_catalog['drinks']["yogourt"])