这是我做的Python字典模块的知识总结,仅供参考。
字典简单使用:
alien_0={'color':'green','points':5}
print(alien_0['color'])
print(alien_0['points'])
运行结果:
green
5
在Python中,字典是一系列键_值对,与键相关联的值可以是数字、字符串、列表乃至字典。键和值之间用冒号分隔,而键_值对之间用逗号分隔。
字典定义使用:
alien_0={'color':'green','points':5}
字典访问:
print(alien_0['color'])
添加键_值对:
alien_0['x_position']=0
alien_0['y_position']=25
字典修改:
alien_0['color']='yellow'
删除:
del alien_0['points']
遍历所有键_对值:
user_0={
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
for key,value in user_0.items():
print("\nkey: "+key)
print("value: "+value)
运行结果:
key: last
value: fermi
key: first
value: enrico
key: username
value: efermi
即使遍历字典时,键_值对的返回顺序也与存储顺序不同。
遍历字典中所有键:
for key in user_0.keys():
print(key)
#遍历字典时,会默认遍历所有的键,因此,如果将上述代码中的for key in user_0.keys():
#替换为for key in user_0: ,输出将不变。
for key in user_0:
print(key)
遍历字典中所有的值:
for value in user_0.values():
print(value)
找出列表中独一无二的元素:
for key in set(user_0.keys()):
print(key)
嵌套
字典列表:
alien_0={"color":"green","point":5}
alien_1={"color":"red","point":6}
alien_2={"color":"yellow","point":7}
aliens=[alien_0,alien_1,alien_2]
在字典中存储列表:
pizza={
'toopings':['mushrooms','extra cheese']
}
for tooping in pizza['toopings'][:1]:
print('\t'+ tooping)
在字典中存储字典:
users={
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'peincetion',
},
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris',
},
}
参考书籍《Python编程从入门到实践
2020.7.22_第一周