Beginner's Guide: Python Dictionaries - Key-Value Pairs and Iteration Techniques

1. What is a Dictionary?

In Python, a Dictionary is a key-value pair data structure. It is like a real-life “address book”—you can quickly find the corresponding value using a unique key. For example, you can use “name” as the key to store information like “age” and “phone number” as values, making it more intuitive than a list (which requires index access).

For instance, to record a student’s information, a list might look like [["name", "Xiaoming"], ["age", 18]], while a dictionary is more concise: {"name": "Xiaoming", "age": 18}. You can access the value directly via the key, e.g., student["name"] returns “Xiaoming”.

2. Creating a Dictionary: The Simplest Way is with Curly Braces

A dictionary consists of keys and values, separated by colons :, with key-value pairs separated by commas ,, and enclosed in curly braces {}.

Example:

# Create a dictionary with curly braces
student = {
    "name": "Xiaoming",
    "age": 18,
    "score": 95,
    "hobbies": ["Basketball", "Programming"]  # Values can be any type, including lists
}

Notes:
- Keys must be immutable types (e.g., strings, numbers, tuples). Mutable types like lists or dictionaries cannot be keys (will cause an error).
- Values can be any type (numbers, strings, lists, other dictionaries, etc.).

3. Accessing Dictionary Elements: “Look Up” Values by Key Name

To retrieve a value from a dictionary, use the key name with square brackets []. If the key does not exist, a KeyError is raised. Thus, the get() method is recommended for safety (returns None or a custom default value if the key is missing).

Example:

student = {"name": "Xiaoming", "age": 18, "score": 95}

# 1. Direct key access (raises error if key is missing)
print(student["name"])  # Output: Xiaoming
# print(student["gender"])  # Error! KeyError: 'gender'

# 2. Using get() (safer; returns None or a default value if key is missing)
print(student.get("age"))       # Output: 18
print(student.get("gender", "Unknown"))  # Output: Unknown (default value)

4. Modifying, Adding, and Deleting Elements

Dictionaries are mutable, so you can modify, add, or delete key-value pairs at any time.

  • Modify/Add: If the key exists, assignment updates the value; if not, it adds a new key-value pair.
  student = {"name": "Xiaoming", "age": 18}

  # Modify existing key
  student["age"] = 19  # Update age to 19
  print(student)  # Output: {'name': 'Xiaoming', 'age': 19}

  # Add new key-value pair
  student["score"] = 95  # Add score
  print(student)  # Output: {'name': 'Xiaoming', 'age': 19, 'score': 95}
  • Delete Elements: Use del or pop().
  student = {"name": "Xiaoming", "age": 18, "score": 95}

  # 1. del statement (no return value)
  del student["age"]  # Delete age
  print(student)  # Output: {'name': 'Xiaoming', 'score': 95}

  # 2. pop() method (returns the deleted value)
  age = student.pop("score")  # Delete score and return 95
  print(student)  # Output: {'name': 'Xiaoming'}
  print(age)      # Output: 95

5. Iterating Over a Dictionary: Three Common Techniques

When iterating, focus on keys, values, or key-value pairs. Python offers three methods:

  1. Iterate over all keys: Use for key in 字典 or 字典.keys().
   student = {"name": "Xiaoming", "age": 18, "score": 95}

   for key in student:
       print(key)  # Output: name, age, score (Python 3.7+ preserves insertion order)
  1. Iterate over all values: Use for value in 字典.values().
   for value in student.values():
       print(value)  # Output: Xiaoming, 18, 95
  1. Iterate over all key-value pairs: Use for key, value in 字典.items().
   for key, value in student.items():
       print(f"{key}: {value}")  # Output: name: Xiaoming, age: 18, score: 95

6. Useful Dictionary Tips

  • Check if a key exists: Use the in operator.
  student = {"name": "Xiaoming", "age": 18}
  print("name" in student)  # Output: True (key exists)
  print("gender" in student)  # Output: False (key does not exist)
  • Get dictionary length: Use len().
  print(len(student))  # Output: 2 (two key-value pairs)
  • Merge dictionaries: Use update(). Duplicate keys will be overwritten.
  dict1 = {"a": 1, "b": 2}
  dict2 = {"b": 3, "c": 4}
  dict1.update(dict2)  # Merge dict2 into dict1
  print(dict1)  # Output: {'a': 1, 'b': 3, 'c': 4} (b's value is overwritten)

7. Summary

Dictionaries are flexible and efficient in Python, centered around key-value pairs. They enable quick value lookup via keys, making them ideal for storing “related data” (e.g., user information, configuration parameters). Key points to remember:
- Create with {} or dict(). Keys must be immutable (strings, numbers, tuples).
- Access values via 字典[key] or 字典.get(key) (safer).
- Modify/add elements via assignment, delete with del or pop().
- Iterate using for key in 字典, for value in 字典.values(), or for key, value in 字典.items().

Practice with these techniques to master dictionaries for real-world problems!

Xiaoye