字典
1. 定义
字典由一系列键值对(key-value pairs)组成,键值对之间用逗号分隔,并且放在花括号(brace)内,简单的字典如下
alien_0={"color":"green","points":5}
print(alien_0['color'])
2. 使用字典
2.1 访问字典中的值
要获得键相应的值,可依此指定字典名和放在方括号内的键名,如下
print(alien_0['color']) # 注意不可以由值获取键,即不能print(alien_0['green'])
2.2 添加、删除键值对和修改字典中的值
alien_0['x_position']=0 # 添加键值对"'x_position':0"
alien_0['y_position']=25 # 添加键值对 "'y_position':25"
alien_0['color']='red' # 修改'color'键相应的值为'red'
del alien_0['color'] # 删除'color'相应的键值对
3. 遍历字典
3.1 遍历字典中所有的键值对
user_0 = {'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items(): # 注意使用items()方法访问键值对
print("
Key: " + key)
print("Value: " + value)
注意遍历字典时,键值对的返回顺序也可能与储存顺序不同,python不关心存储顺序,只追踪键与值之间的关系
3.2 遍历所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys(): # 注意用keys()方法访问键
print(name.title())
if 'erin' not in favorite_languages.keys(): # keys()方法实际上返回一个列表,里面元素包含所有键
print("erin, please take our poll!")
for name in favorite_languages: # 该行同样默认访问键,前面加上keys()更显而易见
print(name.title())
3.3 按顺序遍历所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()): # 加个sored()临时排序
print(name.title())
3.4 按顺序遍历所有值
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for language in sorted(favorite_languages.values()): # 使用values()访问值
print(language.title())
4. 嵌套(nesting)
4.1 字典列表
简单创建字典列表如下
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)
稍微复杂一点,用for循环批量生成
# Make an empty list for storing aliens.
aliens = []
# Make 30 green aliens.
for alien_number in range (0,30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] = 15
# Show the first 5 aliens:
for alien in aliens[0:5]:
print(alien)
print("...")
4.2 字典里嵌套列表(元组)
字典中的键可以是数字也可以是string,但不能是列表或者字典的形式,而值却可以是列表或者字典的形式,如下
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
print(pizza['toppings'][0]) # 简单打印,前一个方括号指定键值,后者指定列表序列号
# Summarize the order.
print("You ordered a " + pizza['crust'] + "-crust pizza " +
"with the following toppings:")
for topping in pizza['toppings']:
print(" " + topping)
4.3 字典里嵌套字典
users = {'aeinstein': {'first': 'albert',
'last': 'einstein',
'location': 'princeton'},
'mcurie': {'first': 'marie',
'last': 'curie',
'location': 'paris'},
}
print(users['mcurie']['first']) # 简单打印字典users键'mcurie'对应值中的键'first'所对应的值
for username, user_info in users.items():
print("
Username: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print(" Full name: " + full_name.title())
print(" Location: " + location.title())