#字典遍历
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'rudy',
'phil':'python',
}
for key,value in favorite_languages.items():
print(f"key:{key.title()} \nvalue:{value.title()}" ) #打印出键和值
friends = ['phil','jen']
for name in favorite_languages.keys(): #使用keys()可不需要字典的值
print(f"Hello,{name.title()}")
if name in friends: #判断朋友是否在列表中
language = favorite_languages[name].title()
print(f"\t{name.title()}, I see you love {language}")
for value in favorite_languages.values(): #使用.values()可访问键的值
print(value)
print('-----------------')
#字典嵌套
aliens = []
#创建30个绿色的外星人
for alien_num in range(30):
alien = {'color':'green','point':'5','speed':'slow'}
aliens.append(alien)
for name in aliens:
print(name)
print("外星人的个数:",len(aliens))
print('-----------------')
#将前三个外星人修改为黄色、速度为中等且值10分
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['point'] = '10'
alien['speed'] = 'medium'
for name in aliens:
print(name)
print('-----------------')
#在字典中存储列表
favorite_language = {
'jen':['python','java'],
'sarah':['c','c++'],
'edward':['rudy','go'],
'phil':['python'],
}
for name,languages in favorite_language.items():
print(f"\n{name.title()}'s favorite languages are:")
for language in languages:
print(f"\t{language.title()}")
python笔记-字典
最新推荐文章于 2024-09-09 00:00:00 发布