Skip to content

Python Dictionaries

键-值映射使用 dicts: creation, access, 方法, iteration, and nested 结构.

你将学到

  • 创建 dictionaries and access 值通过键
  • 添加, 更新, and 删除键-值 pairs
  • Iterate over 键, 值, and 项
  • Use 获取(), setdefault(), and dict comprehensions
  • 工作使用 nested dictionaries

概念讲解

Creating Dictionaries

A dictionary (dict) is an unordered collection of key-value pairs. Keys must be hashable (immutable types like str, int, tuple), and each key is unique:

empty = {}
user = {"name": "Ada", "age": 25, "role": "admin"}
scores = dict(math=90, science=85, english=88)

Dictionaries are Python's most powerful data structure for lookups — accessing a value by key is O(1) on average. They are the natural representation for JSON, configuration, and any named-field data.

Accessing and Modifying

user = {"name": "Ada", "age": 25}

# Access — KeyError if key missing
print(user["name"])        # Ada

# Safe access with get() — returns None or a default
print(user.get("email"))            # None
print(user.get("email", "N/"))     # N/A

# Add or update a key
user["email"] = "ada@示例.com"
user["age"] = 26  # update existing

# Delete
del user["email"]
user.pop("age")   # remove and return value

Always use .获取() when a key might be missing — it avoids KeyError and lets you specify a default. This is one of the most important dict patterns.

Iterating

user = {"name": "Ada", "age": 25, "role": "admin"}

# Keys only
for key in user:
    print(key)

# Keys and values together
for key, value in user.items():
    print(f"{键} = {值}")

# Values only
for value in user.values():
    print(value)

The .项() method is the most useful — it lets you loop over key-value pairs simultaneously. In Python 3.7+, dictionaries maintain insertion order, so iteration is predictable.

Useful Methods

  • .获取(键, 默认) — safe access with a fallback
  • .setdefault(键, 默认) — get or set in one operation
  • .更新() — merge another dict
  • .键() / .值() / .项() — view objects
  • in — check if a key exists
config = {"调试": False}
config.setdefault("port", 8080)   # adds port only if missing
config.update({"调试": True, "host": "localhost"})
print("port" in config)           # True

Dict Comprehensions

Just like list comprehensions, but for dictionaries:

squares = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

prices = {"apple": 1.5, "banana": 0.5}
doubled = {k: v * 2 for k, v in prices.items()}

Nested Dictionaries

Dictionaries can be nested to represent structured data:

users = {
    "ada": {"age": 25, "role": "admin"},
    "bob": {"age": 30, "role": "用户"},
}
print(users["ada"]["role"])  # admin

For deeply nested structures, consider 集合.defaultdict or data classes for cleaner access.

示例代码

              # Creating dictionaries
user = {"name": "Ada", "age": 25, "role": "admin"}
scores = dict(math=90, science=85, english=88)

# Accessing — use get() for safety
print(user["name"])              # Ada
print(user.get("email"))         # None
print(user.get("email", "N/A"))  # N/A

# Adding and updating
user["email"] = "[email protected]"
user["age"] = 26
print(user)

# Iterating
for key, value in user.items():
    print(f"  {key} = {value}")

# Useful methods
config = {"debug": False}
config.setdefault("port", 8080)
config.update({"host": "localhost"})
print(config)

# Dict comprehension
squares = {x: x ** 2 for x in range(5)}
print(squares)  # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# Nested dictionaries
users = {
    "ada": {"age": 25, "role": "admin"},
    "bob": {"age": 30, "role": "user"},
}
print(users["ada"]["role"])  # admin

# Deleting
del user["email"]
print(user.pop("age"))  # 26
print(user)
            

Demonstrates dict creation, safe access 使用获取(), 添加/更新/删除键, iteration 使用项(), setdefault and 更新, dict comprehensions, and nested dict access.

动手试一试

  • JSON Formatter

    Python dicts 映射 directly 到 JSON 对象 — 格式 and 验证它们.

  • CSV 到 JSON

    Converting CSV 行到 dicts 是常见数据 transformation.

常见错误

错误写法

Accessing missing 键使用 dict[键] 相反的 dict.获取(键)

正确做法

dict[键] raises KeyError 如果键 做不 exist. Use dict.获取(键) 哪个返回无, or dict.获取(键, 默认) 到 specify fallback. 这个是 safest access 模式.

错误写法

Using 列表 as dictionary 键

正确做法

Dictionary 键必须是 hashable (不可变). 列表 and dicts 是不 hashable — use tuple 相反. frozenset 能是 used as 键如果你 需要设置-如键.

相关代码片段

相关速查表

练习 Python Dictionaries

10 个练习

练习 Python Dictionaries

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误