python(三)——字典
字典
字典的键只能是除了字典和列表外的其他类型
比如:int型,float型,bool型,元组等
而字典的value值可以是任何类型
1)字典及其访问与创建
1)字典是一系列键-值对。每一个键都与一个值相关联,可通过键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典,任何对象都可以称为字典中的值。
2)访问字典中的值时,通过键来访问。
3)创建空字典时,用大括号。alien_0 = {}
4)使用 字典名.get(key)方法能够在key值不存在时不报错,返回None继续执行后续代码。
如:
>>> alien_0 = { 'color':'green','points':'5'}
>>> print(alien_0)
{'color': 'green', 'points': '5'}
>>> print(alien_0['color'])
green
>>> print(alien_0['points'])
5
2)添加键-值对
-
法一:
要添加键-值对,依次指定字典名、用方括号括起键和相关联的值即可。>>> alien_0['x_position'] = 0 >>> alien_0['y_position'] = 25 >>> print(alien_0) {'color': 'green', 'points': '5', 'x_position': 0, 'y_position': 25}
-
法二:
setdefault(key,value)方法,若key值存在,则不改变value值,若key值不存在,则添加新的。info_dict = {'name':'lin','age':21} info_dict.setdefault('name','kk') info_dict.setdefault('job','学生') print(info_dict)
-
法三:
字典1.update(字典2)
把字典2合并到字典1中,key值存在的更新其value值,不存在则增加新的键值对。info_dict = {'name':'lin','age':21,'job':'学生'} other = {'age': '23','weigh':70} info_dict.update(other) print(info_dict)
3)修改字典的值
直接对键进行重新赋值。
>>> print(alien_0['color'])
green
>>> alien_0['color']='yellow'
>>> print(alien_0['color'])
yellow
4)删除键-值对
- 法一:del
用del语句可将相应的键-值对彻底删除,删除了的键-值对永远的消失了。
>>> print(alien_0)
{'color': 'yellow', 'points': '5'}
>>> del alien_0['color']
>>> print(alien_0)
{'points': '5'}
- 法二:pop
- 法三:clear
遍历字典
1)items()方法
items()方法能够返回一个键-值对列表。
注:遍历字典键-值对返回的顺序与存储顺序不一定相同,python不关心键-值对的存储顺序,只关注键与值的对应关系。
>>> for key,value in alien_0.items():
... print(key,value)
color green
points 5
x_position 0
y_position 25
2)keys()方法
keys()方法只返回键,不返回值。
注:若在遍历字典时不表明使用的方法,默认使用keys()方法。
>>> alien_0 = {'color': 'green', 'points': '5', 'x_position': 0, 'y_position': 25}
>>> for key in alien_0.keys():
... print(key)
color
points
x_position
y_position
3)values()方法
values()方法只返回值,不返回键。
注:该方法返回值没有考虑是否重复的问题,所以重复的值也会一样返回。此时可用set()集合,将重复值剔除,该集合中每个值必须唯一。
>>> alien_0['z_position']=0
>>> print(alien_0)
{'color': 'green', 'points': '5', 'x_position': 0, 'y_position': 25, 'z_position': 0}
>>> for value in alien_0.values():
... print(value)
...
green
5
0
25
0
>>>
>>> for value in set(alien_0.values()):
... print(value)
...
5
0
green
25
字典嵌套
1)列表中为字典
>>> aliens = []
>>> for alien_number in range(5):
... new_alien = {'color':'green','point':'5'}
... aliens.append(new_alien)
>>> print(aliens)
[{'color': 'green', 'point': '5'}, {'color': 'green', 'point': '5'}, {'color': 'green', 'point': '5'}, {'color': 'green', 'point': '5'}, {'color': 'green', 'point': '5'}]
>>> for alien in aliens[0:3]:
... print(alien)
...
{'color': 'green', 'point': '5'}
{'color': 'green', 'point': '5'}
{'color': 'green', 'point': '5'}
2)字典中存储列表
>>> type_c = {
... 'english':['a','b','c','d','e'],
... 'number':[1,2,3,4,5],
... 'English':['A','B','C','D','E']}
>>> for key,value in type_c.items():
... print("Type is "+key)
... for v in value:
... print("\t"+str(v))
...
Type is english
a
b
c
d
e
Type is number
1
2
3
4
5
Type is English
A
B
C
D
E
3)字典中存储字典
>>> users = {
... 'aeinstrin':{
... 'first':'albert',
... 'last':'einstein',
... 'location':'princeton',
... },
... 'mcurie':{
... 'first':'marie',
... 'last':'curie',
... 'location':'paris',
... },
... }
>>> for username,user_info in users.items():
... print("\nUsername:"+username)
... full_name = user_info['first']+" "+user_info['last']
... location = user_info['location']
... print("\tFull name:"+full_name)
... print("\tLocation:"+location)
...
Username:aeinstrin
Full name:albert einstein
Location:princeton
Username:mcurie
Full name:marie curie
Location:paris