字典的练习
#字典存储外星人的颜色和点数
alien_0 = {"color":"green","points":5}
print(alien_0["color"])
print(alien_0["points"])
遍历字典
#key-value
favorite_languages = {
"jen" : "python",
"sarah" : "c",
"edwrd" : "ruby",
"phil" : "python",
}
for name, language in favorite_languages.items():
print(name.title()+"'s favorite language is " + language.title() + ".")
遍历字典中所有key,用keys()方法
for name in favorite_languages.keys():
print(name.title())
if "erin" not in favorite_languages.keys():
print("Erin, please take our poll")
按顺序遍历字典中所有键(利用sorted()函数)
for name in sorted(favorite_languages.keys()):
print(name.title())
遍历字典中所有的值,使用values()方法
for language in favorite_languages.values():
print(language.title())
剔除重复项,可使用集合set
for language in set(favorite_languages.values()):
print(language.title())
有时候需要将一系列字典存储在列表中,或将列表作为值存储在字典中
#字典列表,在列表中存储字典
alien_0 = {'color':'green','points':2}
alien_1 = {'color':'yellow','points':4}
alien_2 = {'color':'red','points':6}
aliens = [alien_0,alien_1,alien_2]
for alien in aliens:
print(alien)
#字典列表练习2
#创建一个空列表
aliens = []
#创建30个alien
for alien_number in range(0,30):
new_alien = {'color':'green','points':2,'speed':'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['points'] = 4
alien['speed'] = 'medium'
for alien in aliens[0:5]:
print(alien)
print('...')
在字典中存储列表
pizza = {'crust':'thick','toppings':['mushrooms','extra cheese']}
print("Your ordered a " + pizza['crust'] + "- crust pizza " + "with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
在字典中存储字典
users = {'aeinstein':{'first':'albert','last':'einstein','location':'princetion'},'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())
2370



被折叠的 条评论
为什么被折叠?



