python基础之字典
字典是一系列键值对,每个键都与一个值相关联。
访问字典的值
alien = {'color':'green','points':5}
new_points = alien['points']
print("You just earned " + str(new_points) + " points!")
#get访问到没有的key也不会报错
alien = {'color':'green','points':5}
new_points = alien.get('points')
new_none = alien.get('name')
new_name = alien.get('name','huny')
print(new_points)
print(new_none)
print(new_name)
添加键值对
alien = {'color':'green','points':5}
alien['x_position'] = 0
alien['y_position'] = 25
print(alien)
修改字典的值
alien = {'color':'green','points':5}
alien['color'] = 'yellow'
print(alien)
删除键值对
alien = {'color':'green','points':5}
print(alien)
del alien['points']
print(alien)
遍历字典
user = {'username':'efermi','first':'enrico','last':'fermi'}
for key,value in user.items():
print("\nkey:" + key)
print('value:' + value)
遍历字典的键
user = {'username':'efermi','first':'enrico','last':'fermi'}
for key in user.keys():
print("\nkey:" + key)
遍历字典的值
user = {'username':'efermi','first':'enrico','last':'fermi'}
for value in user.values():
print("\nvalue:" + value)
字典嵌套列表
favorite_languages = {
'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
}
for name,languages in favorite_languages.items():
print("\n" + name.title() + "is favorite_languages are:")
for language in languages:
print("\t" + language.title())
字典嵌套字典
users = {
'aeinstein':{
'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.title())
print("\tlocation: " + location.title())
本文来自博客园,作者:Harry_666,转载请注明原文链接:https://www.cnblogs.com/harry66/p/13765188.html