1、遍历整个字典的键-值对
items()方法返回一个键-值对列表,for 循环依次将每个键—值对存储到指定的两个变量中。
使用元组和列表遍历方法遍历字典:
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():print("\nKey: " + key)print("Value: " + value)
python返回:
Key: last
Value: fermiKey: first
Value: enricoKey: username
Value: efermi
2、遍历字典中的所有键
keys()方法返回一个键列表,for 循环依次将每个键存储到指定的变量中。
遍历所有键:
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():print(name.title())
python返回:
Jen
Sarah
Phil
Edward
备注:keys()方法返回值是列表,所以可以进行sorted排序,下面的values()方法一样。
3、遍历字典中的所有值
values()方法返回一个值列表,for 循环依次将每个值存储到指定的变量中。
遍历所有值:
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for language in favorite_languages.values():print(language.title())
python返回:
Python
C
Python
Ruby
备注:keys()方法返回值是列表,所以可以进行sorted排序,下面的values()方法一样。
4、嵌套
正如列表的元素可以是列表一样,列表的元素也可以是字典;字典的值可以是列表,也可以是字典(字典的值可以是列表或字典,但键不可以是列表或字典)。
列表元素是字典:
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)
python返回:
{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}
字典的值是列表:
# 存储所点比萨的信息
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)
python返回:
You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese
字典的值是字典:
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())
python返回:
Username: aeinsteinFull name: Albert EinsteinLocation: PrincetonUsername: mcurieFull name: Marie CurieLocation: Paris
备注:直接调用时,调用方法相当于二维数组users[mcurie][first]