alien_0 = {'color': 'green','points': 5 }
print(alien_0['color'])
print(alien_0['points'])
#添加键值对
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
#修改
alien_0['color'] = 'yellow'
print(alien_0)
#删除
del alien_0['points']
print(alien_0)
#注意书写规范,此处缩进4个空格,一个tab键
favorite_languages = {
'jen' : 'python',
'sarah' : 'c',
'edward' : 'ruby',
'phil' : 'python',
}
print("sarah's favorite language is " +
favorite_languages['sarah'].title()+
".")
#遍历字典键值对列表
for name,language in favorite_languages.items():
print('\nname:'+name)
print('language:'+language)
#遍历字典的键
for name in favorite_languages.keys():
print('\nname:'+name.title())
#不加方法,默认遍历键,使用上面的增加可读性
for name in favorite_languages:
print('\nname:'+name.title())
#对遍历进行排序,
for name in sorted(favorite_languages.keys()):
print('\nname:'+name.title())
#遍历字典的值
for language in favorite_languages.values():
print('\nlanguage:'+language.title())
print('\n')
#去除重复的值,然后排序
for language in sorted(set(favorite_languages.values())):
print('\nlanguage:'+language.title())
#字典列表
alien_0 = {'color' : 'green','points' : 5}
alien_1 = {'color' : 'yellow','points' : 10}
alien_2 = {'color' : 'red','points' : 15}
aliens = [alien_0,alien_1,alien_2]
print(aliens)
#创建30个外星人,
aliens = []
for alien_number in range(30):
new_alien = {'color' : 'green','points' : 5,'speed': 'slow'}
aliens.append(new_alien)
#显示前5个
for alien in aliens[:5]:
print(alien)
print('...')
#显示总数
print("total number of aliens is "+str(len(aliens)))
#修改
for alien in aliens[:4]:
if alien['color'] == 'green':
alien['color'] = 'black'
for alien in aliens[:4]:
print(alien)
#字典里嵌套列表
alien_0 = {
'color' : ['green','red','yellow'],
'points' : 5,
}
for color in alien_0['color']:
print('\t'+color)
favorite_languages = {
'jen' : ['python','ruby'],
'sarah' : ['c'],
'edward' : ['ruby','go'],
'phil' : ['python','haskell'],
}
for name,languages in favorite_languages.items():
print('name:'+name.title())
if(len(languages) < 2):
print('favorite language is ')
print(languages[0])
print('\n')
else:
print('favorite languages are ')
for language in languages:
print(language)
print('\n')
#字典内存储字典
users = {
'aeinstein':{
'first':'albert',
'last':'einstein',
'location':'princeton',
},
'murie':{
'first':'maire',
'last':'curie',
'location':'paris',
}
}
for username,userinfo in users.items():
print('username:'+username)
fullname = userinfo['first']+' '+userinfo['last']
location = userinfo['location']
print('fullname:'+fullname)
print('location:'+location)
print('\n')