1 字典功能
字典是可变容器模型,且可存储任意类型对象;
字典的每个键值对 <key: value> 用冒号 : 分割,每个对之间用逗号(,)分割,整个字典包括在花括号 {} 中 ,格式如下所示:
d = {key1 : value1, key2 : value2, key3 : value3 }
键必须是唯一的,但值则不必。
值可以取任何数据类型,但键必须是不可变的,如字符串,数字。
一个简单的字典实例:person = {"name": "Alice", "age": 25, "city": "New York"}
2 创建字典
2.1 使用{ }
创建字典
person = {"name": "Alice", "age": 25, "city": "New York"}
较长的字典可分行书写
favorite_languages = {'jen': 'python','sarah': 'c','edward': 'rust','phil': 'python',}if 'erin' not in favorite_languages.keys():print("Erin, please take our poll!")friends = ['phil', 'sarah']
for name in favorite_languages.keys():print(f"Hi {name.title()}.")if name in friends:language = favorite_languages[name].title()print(f"\t{name.title()}, I see you love {language}!")
2.2 使用 dict() 函数创建字典
person = dict(name="Bob", age=30, city="Los Angeles")
2.3 从列表的键值对元组创建字典
items = [("apple", 1), ("banana", 2), ("orange", 3)]
fruit_counts = dict(items)
3 访问字典中的元素
person = {"name": "Alice", "age": 25, "city": "New York"}
访问元素:使用方括号 [] 通过键访问字典中的单个值。
只访问键:使用 keys() 方法获取所有键,并可以通过循环遍历。
只访问值:使用 values() 方法获取所有值,并可以通过循环遍历。
访问键值对:使用 items() 方法获取所有键值对,并可以通过循环遍历每个键值对。
3.1 访问字典中的键和值
3.1.1 访问单个元素:[ ]
通过[ ]
访问单个键值对:通过指定键来获取对应的值,键不存在时会引发错误或返回默认值。
person = {"name": "Alice", "age": 25, "city": "New York"}
name = person["name"]
print(name) # 输出:Alice
3.1.2 访问单个元素:get()
使用 get() 方法
访问(更安全)
person = {"name": "Alice", "age": 25, "city": "New York"}
name = person.get("name")
age = person.get("age")
print(name, age) # 输出:Alice 25
# 如果键不存在,返回默认值
country = person.get("country", "Unknown")
print(country) # 输出:Unknown
建议优先使用 get() 方法来访问字典中的值,以避免因键不存在而导致的错误。
3.1.2 遍历所有元素键值对:逐个[ ]
alien_0 = {'color': 'green', 'speed': 'slow'}# 使用方括号访问每个元素
print(alien_0['color']) # 输出:green
print(alien_0['speed']) # 输出:slow
3.1.2.2 遍历所有键值对: for + [ ]
person = {"name": "Alice", "age": 25, "city": "New York"}# 遍历字典的键,然后使用方括号访问对应的值
for key in person:value = person[key]print(f"Key: {key}, Value: {value}")
output
Key: name, Value: Alice
Key: age, Value: 25
Key: city, Value: New York
person = {"name": "Alice", "age": 25, "city": "New York"}
for key, value in person():print()
# 输出:
# name: Alice
# age: 25
# city: New York
3.1.2.3 遍历所有键值对: items()
使用 items()
方法获取字典中的所有元素的键和值,然后通过循环访问。
person = {"name": "Alice", "age": 25, "city": "New York"}
for key, value in person.items():print(f"{key}: {value}")
# 输出:
# name: Alice
# age: 25
# city: New York
alien_0 = {'color': 'green', 'speed': 'slow'}# 获取字典的所有键值对
items = alien_0.items()
print(items) # 输出:dict_items([('color', 'green'), ('speed', 'slow')])# 遍历字典的所有键值对
for key, value in alien_0.items():print(f"{key}: {value}")
# 输出:
# color: green
# speed: slow
3.2 只访问字典中的键
3.2.1 只访问字典中的键:变量名输出
favorite_languages = {'jen': 'python','sarah': 'c','edward': 'rust','phil': 'python',}print("The following languages have been mentioned:")
for language in favorite_languages:print(language)
output:
jen
sarah
edward
phil
3.2.2 只访问字典中的键 :keys()
alien_0 = {'color': 'green', 'speed': 'slow'}# 获取字典的所有键
keys = alien_0.keys()
print(keys) # 输出:dict_keys(['color', 'speed'])# 遍历字典的所有键
for key in alien_0:print(key)
# 输出:
# color
# speed
3.3 只访问字典元素的值
3.3.1 访问单个元素值: get() 方法
get() 方法是安全访问字典元素的推荐方式,尤其是在不确定字典中是否存在某个键时。如果字典中存在指定的键,它会返回该键对应的值;如果不存在,则返回一个默认值,而不是抛出错误。
alien_0 = {'color': 'green', 'speed': 'slow'}# 尝试获取键 'points' 对应的值
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)
对比
person = {“name”: “Alice”, “age”: 25, “city”: “New York”}
避免错误:使用 get() 方法可以避免因字典中没有指定键而引发的 KeyError。
提供默认值:可以指定一个默认值,使代码更具可读性和健壮性。
与[]
直接访问的区别
直接访问:alien_0[‘points’]
如果键不存在,会抛出 KeyError。 get() 方法:如果键不存在,返回默认值(如果没有指定默认值,则返回 None)。
3.3.2 通过方法values()
所有元素的值
访问所有值,无需for循环,可直接输出所有值
alien_0 = {'color': 'green', 'speed': 'slow'}# 获取字典的所有值
values = alien_0.values()
print(values) # 输出:dict_values(['green', 'slow'])# 遍历字典的所有值
for value in alien_0.values():print(value)
# 输出:
# green
# slow
3.4 排序后访问
sorted
favorite_languages = {'jen': 'python','sarah': 'c','edward': 'rust','phil': 'python',}for name in sorted(favorite_languages.keys()):print(f"{name.title()}, thank you for taking the poll.")
4 修改字典中的元素
person = {"name": "Alice", "age": 25, "city": "New York"}# 修改现有键对应的值
person["age"] = 26
print(person) # 输出:{'name': 'Alice', 'age': 26, 'city': 'New York'}# 添加新的键值对
person["country"] = "USA"
print(person) # 输出:{'name': 'Alice', 'age': 26, 'city': 'New York', 'country': 'USA'}
5 删除字典中的元素
person = {"name": "Alice", "age": 25, "city": "New York"}# 使用 pop() 方法删除指定键及其关联值
age = person.pop("age")
print(age) # 输出:25
print(person) # 输出:{'name': 'Alice', 'city': 'New York'}# 使用 del 语句删除元素
del person["city"]
print(person) # 输出:{'name': 'Alice'}# 清空字典
person.clear()
print(person) # 输出:{}
6 遍历字典
person = {"name": "Alice", "age": 25, "city": "New York"}# 遍历字典的键
for key in person:print(key)
# 输出:
# name
# age
# city# 遍历字典的值
for value in person.values():print(value)
# 输出:
# Alice
# 25
# New York# 遍历字典的键值对
for key, value in person.items():print(f"{key}: {value}")
# 输出:
# name: Alice
# age: 25
# city: New York
7 检查某个键或值是否在字典中
person = {"name": "Alice", "age": 25, "city": "New York"}# 检查键是否存在于字典中
has_name = "name" in person
print(has_name) # 输出:True# 检查值是否存在于字典中
has_alice = "Alice" in person.values()
print(has_alice) # 输出:True
8 字典的嵌套
# 字典中嵌套字典
students = {"Alice": {"id": 1, "grade": "A"},"Bob": {"id": 2, "grade": "B"},"Charlie": {"id": 3, "grade": "C"}
}# 访问嵌套字典中的元素
alice_grade = students["Alice"]["grade"]
print(alice_grade) # 输出:"A"# 修改嵌套字典中的元素
students["Bob"]["grade"] = "A"
print(students["Bob"]) # 输出:{'id': 2, 'grade': 'A'}
8.1 字典的嵌套定义
users = {'aeinstein': {'first': 'albert','last': 'einstein','location': 'princeton',},'mcurie': {'first': 'marie','last': 'curie','location': 'paris',},}for username, user_info in users.items():print(f"\nUsername: {username}")full_name = f"{user_info['first']} {user_info['last']}"location = user_info['location']print(f"\tFull name: {full_name.title()}")print(f"\tLocation: {location.title()}")
8.2 在字典中嵌套列表
pizza = {'crust': 'thick','toppings': ['mushrooms', 'extra cheese'],}# Summarize the order.
print(f"You ordered a {pizza['crust']}-crust pizza ""with the following toppings:")for topping in pizza['toppings']:print(f"\t{topping}")
8.3 将字典嵌套入列表
8.3.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)
8.3.2 通过循环将字典嵌套入列表
# Make an empty list for storing aliens.
aliens = []# Make 30 green aliens.
for alien_number in range(30):new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}aliens.append(new_alien)# Show the first 5 aliens.
for alien in aliens[:5]:print(alien)
print("...")# Show how many aliens have been created.
print(f"Total number of aliens: {len(aliens)}")
output
{‘color’: ‘yellow’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘yellow’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘yellow’, ‘points’: 10, ‘speed’: ‘medium’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
…
Total number of aliens: 30