字典
字典操作
#向字典中添加键-值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
>>>{'color': 'green', 'points': 5}
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
>>>{'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}
#修改字典中的值
alien_0 = {'color': 'green', 'points': 5}
alien_0['color'] = 'yellow'
print(alien_0)
>>>{'color': 'yellow', 'points': 5}
#对一个能够以不同速度移动的外星人的位置进行跟踪。
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
#向右移动外星人
#根据外星人当前速度决定将其移动多远
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
#新位置等于老位置加上增量
alien_0['x_position'] = alien_0['x_position'] + x_increment
print(alien_0)
>>>{'x_position': 2, 'y_position': 25, 'speed': 'medium'}
#删除键-值对
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['color'] #删除使用del,删除的键—值对永远消失了。
print(alien_0)
>>>{'points': 5}
#使用一个字典来存储一个熟人的信息,该字典应包含键first_name 、last_name 、age 和city 。将存储在该字典中
#的每项信息都打印出来。
user = {'first_name':'jacky','last_name':'zhao','age':30,'city':'shanghai'}
for i in user:
print(i + ':' + str(user[i]))
>>>first_name:jacky
>>>last_name:zhao
>>>age:30
>>>city:shanghai
#格式化打印字典键-值
a = {'ls':'遍历当前文件夹','mkdir':'建立文件夹','rm':'删除文件或文件夹','top':'显示系统进程'}
for i in a:
print(i + ':', a[i])
>>>ls: 遍历当前文件夹
>>>mkdir: 建立文件夹
>>>rm: 删除文件或文件夹
>>>top: 显示系统进程
line1=""
line2=""
for i,v in a.items():
line1+="\t%s"%i
line2+="\t%s"%v
print (line1,'\n' ,line2)
>>>ls mkdir rm top
>>>遍历当前文件夹 建立文件夹 删除文件或文件夹 显示系统进程
#遍历字典
user = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key,value in user.items():
print('Key:' + key)
print('Valune:' + value + '\n')
>>>Key:username
>>>Valune:efermi
>>>
>>>Key:first
>>>Valune:enrico
>>>
>>>Key:last
>>>Valune:fermi
#遍历字典中的元素
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys(): #打印字典中所用的key
print(name.title())
# >>>Jen
# >>>Sarah
# >>>Edward
# >>>Phil
for language in favorite_languages.values(): #打印字典中的所有value
print(language.title())
>>>Python
>>>C
>>>Ruby
>>>Python
for language in set(favorite_languages.values()): #打印字典中所有的value,并用set处理重复值
print(language.title())
>>>Python
>>>C
>>>Ruby
#按顺序遍历字典中的所有键
user = {
'kiven':32,
'seven':20,
'jacky':18,
'alex':20,
}
for name in user.keys(): #不排序直接遍历输出
print(name.title())
>>>Kiven
>>>Seven
>>>Jacky
>>>Alex
for name in sorted(user.keys()): #遍历key并排序输出
print(name.title())
>>>Alex
>>>Jacky
>>>Kiven
>>>Seven
# 创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中。
# 遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢。对于还未参与调查的人,打印一条消息邀请他参与调查。
list = ['user1','user2','user3','user4','user5','user6']
user = {'user1':'yes','user5':'yes'}
for i in list:
if i in user.keys():
print("Thank you for %s's cooperation" % i)
else:
print('%s ,Please cooperate with the investigation!' % i)
#字典列表
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
alien = [alien_0,alien_1,alien_2]
print(alien)
>>>[{'color': 'green', 'points': 5}, {'color': 'yellow', 'points': 10}, {'color': 'red', 'points': 15}]
#定义一个空列表用来存储信息
aliens = []
#创建30个外星人信息
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)
#修改前3个外星人的信息
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
for j in aliens[0:5]:
print(j)
#在字典中存储列表
user = {
'user1':['r','w'],
'user2':['r'],
'user3':['r','w','x'],
'user4':['r']
}
for name,permissions in user.items(): #用for循环打印出字典中的key
print('\n' + name.title() + "'s permission is:")
for permission in permissions: #再用for循环打印出value中的列表中的所有值
print('\t' + permission.title())
#在字典中存储字典
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
}
}
for username,user_info in users.items():
print('\n Username:' + username)
full_name = user_info['first'] + ' ' + user_info['last']
location = user_info['location']
print('\t Full_name:' + full_name.title())
print('\t Location:' + location.title())
>>> Username:aeinstein
>>> Full_name:Albert Einstein
>>> Location:Princeton
>>> Username:mcurie
>>> Full_name:Marie Curie
>>> Location:Paris
#创建多个字典,对于每个字典,都使用一个宠物的名称来给它命名;在每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为pets
#的列表中,再遍历该列表,并将宠物的所有信息都打印出来。
pet1 = {
'类型':'金毛',
'主人':'jacky'
}
pet2 = {
'类型':'萨摩耶',
'主人':'alex'
}
pets = [pet1,pet2]
for pet in pets:
print('\n'+ pet['主人'] + "'s pet" + '\n' '类型:'+ pet['类型'] )
#创建一个名为favorite_places 的字典。在这个字典中,将三个人的名字用作键;对于其中的每个人,都存储他喜欢的1~3个地方。为让这个练
#习更有趣些,可让一些朋友指出他们喜欢的几个地方。遍历这个字典,并将其中每个人的名字及其喜欢的地方打印出来。
favorite_places = {'jacky':['云南','西藏'],'alex':['西藏','哈尔滨','香港'],'bob':['广州','香港']}
for name,placies in favorite_places.items():
print('\n' + str(name) + '喜欢的地方是:')
for place in placies:
print( place)
#创建一个名为cities 的字典,其中将三个城市名用作键;对于每座城市,都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该
#城市的事实。在表示每座城市的字典中,应包含country 、population 和fact 等键。将每座城市的名字以及有关它们的信息都打印出来。
cities = {
'上海':{
'country':'中国',
'population':'2500万',
'fact':'房价贵'
},
'巴黎':{
'country':'法国',
'population':'224万',
'fact':'漂亮'
}
}
for place,info in cities.items():
print('\n'+ '城市:'+ place)
print('Country:' + info['country'] + '\nPopulation:' + info['population'] + '\nFact:'+ info['fact'])

浙公网安备 33010602011771号