字典
python中,字典是一系列键-值对。每个键都与一个值相关联。
可以用键来访问与之相关联的值。
值可以是数字,字符串,列表,字典。
使用方法:
字典名 ={'键名1':值,‘键名2’:值.... ....}
指定键时,python将返回与之相关联的值。
alien_0={'color':'green'}
print(alien_0['color'])
#访问方法
字典是一种动态结构,可随时在其中添加键-值对。
添加键-值对
alien_0={'color':'green'}
print(alien_0)
alien_0['x_position']=0
alien_0['y_position']=25
键-值对的排列顺序与添加顺序不同。
修改字典中的值
依次指定字典名,用方括号括起的键以及与该键相关联的新值
例如
alien_0={'color':'green'}
print(alien_0)
alien_0['color']='red'
print(alien_0)
删除键-值对
可使用del语句将相应的键值对删除,使用时要指定字典名和要删除的键
alien_0={'color':'green','point':5}
print(alien_0)
del alien_0['point']
print(alien_0)
要使用多行来定义字典时,在输入左花括号后按回车键,再在下一行缩进四个空格,指定第一个键-值对,并在后面加上一个逗号之后同上。
遍历字典
遍历所有的键-值对
items()方法返回一个键-值对列表。
favorite_languages ={
'jen':'python',
'sarch':'c',
'edward':'ruby',
'phil':'python',
}
for name,language in favorite_languages.items():
print(name.title()+"'s favorite language is" + language.title()+'.')
遍历字典中的所有键
keys()方法可以输出字典中的键
使用方法:
字典名.keys()
返回值是一个列表,一个包含了字典中所有键的列表
print('---------------------------------------------------------------')
friends = ['phil','sarch']
for name in favorite_languages.keys():
print (name.title())
if name in friends:
print("Hi "+ name.title()+
", I see your favorite language is "+
favorite_languages[name].title()+'!')
print('---------------------------------------------------------------')
在获取字典的元素时,获得顺序是不可预测的。
想要获取特定的顺序返回元素,可以使用函数sorted()来排序
遍历字典中的所有值
values()方法可以输出字典包含的值,他返回的是一个值列表
使用方法:
字典名.values()
print('---------------------------------------------------------------')
print("The following languages have been mentioned :")
for language in favorite_languages.values():
print(language.title())
print('---------------------------------------------------------------')
这样直接提取值可能会存在重复的情况。
set()函数可以去掉列表中的重复项
嵌套
嵌套:将一系列字典存储在列表中,或将列表作为值存储在字典中。
字典列表
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]
for alien in aliens:
print(alien)
在字典中储存列表
print('---------------------------------------------------------------')
pizza ={
'crust': 'thick',
'toppings':['mushrooms','extra cheese'],
}
print("You ordered a "+pizza['crust']+'-crust pizza'+
"with the following toppings:")
for topping in pizza['toppings']:
print('\t'+topping)
print('---------------------------------------------------------------')
在字典中存储字典
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())