Python字典操作详解
1 创建字典
- 使用花括号创建空字典:
empty_dict = {}
print(empty_dict) # 输出: {}
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
print(person) # 输出: {'name': 'Alice', 'age': 25, 'city': 'New York'}
# 使用关键字参数
student = dict(name="Bob", age=20, major="Computer Science")
print(student) # 输出: {'name': 'Bob', 'age': 20, 'major': 'Computer Science'}
# 使用键值对列表
pairs = [("name", "Charlie"), ("age", 30)]
user = dict(pairs)
print(user) # 输出: {'name': 'Charlie', 'age': 30}
2 访问字典元素
person = {"name": "Alice", "age": 25}
print(person["name"]) # 输出: Alice
print(person.get("age")) # 输出: 25
print(person.get("gender")) # 输出: None
print(person.get("gender", "unknown")) # 输出: unknown
3 修改字典
person["age"] = 26
print(person) # 输出: {'name': 'Alice', 'age': 26}
person["email"] = "alice@example.com"
print(person) # 输出: {'name': 'Alice', 'age': 26, 'email': 'alice@example.com'}
person.update({"age": 27, "city": "Boston"})
print(person) # 输出: {'name': 'Alice', 'age': 27, 'email': 'alice@example.com', 'city': 'Boston'}
4 删除字典元素
del person["email"]
print(person) # 输出: {'name': 'Alice', 'age': 27, 'city': 'Boston'}
age = person.pop("age")
print(age) # 输出: 27
print(person) # 输出: {'name': 'Alice', 'city': 'Boston'}
last_item = person.popitem()
print(last_item) # 输出: ('city', 'Boston')
print(person) # 输出: {'name': 'Alice'}
5 字典常用方法
person = {"name": "Alice", "age": 25}
keys = person.keys()
print(list(keys)) # 输出: ['name', 'age']
values = person.values()
print(list(values)) # 输出: ['Alice', 25]
items = person.items()
print(list(items)) # 输出: [('name', 'Alice'), ('age', 25)]
print("name" in person) # 输出: True
print("email" in person) # 输出: False
6 字典遍历
for key in person:
print(key, person[key])
# 输出:
# name Alice
# age 25
for key, value in person.items():
print(f"{key}: {value}")
# 输出:
# name: Alice
# age: 25
7 字典嵌套
students = {
"class1": {
"Alice": {"age": 20, "grade": "A"},
"Bob": {"age": 22, "grade": "B"}
},
"class2": {
"Charlie": {"age": 21, "grade": "A+"}
}
}
print(students["class1"]["Alice"]["age"]) # 输出: 20
8 字典推导式
squares = {x: x**2 for x in range(1, 6)}
print(squares) # 输出: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
original = {"a": 1, "b": 2, "c": 3, "d": 4}
filtered = {k: v for k, v in original.items() if v % 2 == 0}
print(filtered) # 输出: {'b': 2, 'd': 4}
9 字典排序
scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
sorted_by_key = dict(sorted(scores.items()))
print(sorted_by_key) # 输出: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
sorted_by_value = dict(sorted(scores.items(), key=lambda item: item[1]))
print(sorted_by_value) # 输出: {'Charlie': 78, 'Alice': 85, 'Bob': 92}
10 字典合并(Python 3.9+)
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = dict1 | dict2
print(merged) # 输出: {'a': 1, 'b': 3, 'c': 4}
dict1 |= {"d": 5, "e": 6}
print(dict1) # 输出: {'a': 1, 'b': 2, 'd': 5, 'e': 6}
11 总结
Python字典是一种高效的数据结构,提供了灵活的键值存储方式。通过掌握字典的创建、访问、修改、删除等基本操作,以及keys()、values()、items()等核心方法,开发者可以有效处理各种数据组织需求。字典推导式和排序功能进一步增强了其处理能力,而Python 3.9+引入的合并操作符则简化了字典组合操作。熟练运用这些技术将显著提升Python编程的效率和代码质量。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。







