Back to series
· 10 min read

Common Python Dictionary Methods and Iteration


I. Dictionary Operation Basics

A dictionary (dict) is a mutable mapping type that accesses the corresponding value (Value) through a unique key (Key).

user = {
    "name": "Alice",
    "age": 25,
    "city": "Tokyo"
}

The basic dictionary operations can be divided into five categories:

Operation Category Main Methods or Syntax Purpose
Query get(), in, keys() Retrieve data, check whether a key exists
Insert d[key] = value, setdefault() Add key-value pairs
Modify d[key] = value, update() Update existing data
Delete del, pop(), popitem(), clear() Remove key-value pairs
Iterate keys(), values(), items() Access the data in the dictionary

Dictionaries also provide auxiliary methods such as copy() and fromkeys(), as well as merge operations such as | and |=.

II. Dictionary Query Methods

Querying is the most common dictionary operation. Python offers several approaches, which you can choose from according to your needs.

1. Bracket access: d[key]

Retrieve the corresponding value directly through a key.

user = {
    "name": "Alice",
    "age": 25,
    "city": "Tokyo"
}

name = user["name"]
age = user["age"]

print(name)
print(age)

If the key does not exist, a KeyError is raised:

email = user["email"]

Error:

KeyError: 'email'

When to use it:

  • You are certain the key definitely exists.
  • A missing key counts as a program bug.
  • You want to detect as early as possible that the data structure does not match expectations.

2. get(): safely retrieving a value

get() is one of the most commonly used dictionary query methods.

Syntax:

dict.get(key, default=None)

Parameters:

  • key: the key to look up.
  • default: the default value returned when the key does not exist; defaults to None.

Example:

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

print(user.get("name"))
print(user.get("email"))
print(user.get("email", "未填写"))

Output:

Alice
None
未填写

Unlike bracket access, get() does not raise KeyError just because the key does not exist.

Note: when the key exists but its value is None, get() does not return the default value.

data = {
    "name": None
}

print(data.get("name", "Unknown"))  # None
print(data.get("age", "Unknown"))   # Unknown

If you need to distinguish between a key that does not exist and a key that exists but whose value is None, you can use in to test for it, or use a dedicated sentinel object.

3. in: checking whether a key exists

in is used to check whether a certain key exists in the dictionary.

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

print("name" in user)     # True
print("email" in user)    # False

not in is used to check whether a key does not exist:

if "email" not in user:
    print("邮箱尚未填写")

Special note: using in directly on a dictionary checks keys, not values.

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

print("Alice" in user)           # False
print("Alice" in user.values())  # True

4. setdefault(): get or initialize a value

setdefault() is used to get the value of a specified key. If the key does not exist, it writes the specified default value into the dictionary and then returns that value.

Syntax:

dict.setdefault(key, default=None)

Example:

user = {
    "name": "Alice"
}

age = user.setdefault("age", 18)

print(age)
print(user)

Output:

18

{
    "name": "Alice",
    "age": 18
}

If the key already exists, it returns the original value directly and does not overwrite it:

user = {
    "age": 25
}

age = user.setdefault("age", 18)

print(age)  # 25

Common use: grouping by category.

orders = [
    {"category": "book", "amount": 100},
    {"category": "food", "amount": 50},
    {"category": "book", "amount": 80}
]

grouped = {}

for order in orders:
    category = order["category"]

    grouped.setdefault(category, []).append(order)

print(grouped)

If the category does not exist, it creates an empty list; if it already exists, it directly appends the order to the list.

Note that the default value expression of setdefault() is evaluated before the method is called, so even if the key already exists, the default value expression may still be executed.

5. Differences between get() and setdefault()

Both can retrieve values from a dictionary, but their behavior differs.

Aspect get() setdefault()
Key exists Returns original value Returns original value
Key does not exist Returns default value Inserts default value and returns it
Modifies dictionary No Possibly
Common use Safe reading Get or initialize

Example:

data = {}

value = data.get("count", 0)

print(value)
print(data)

Result:

0
{}

Using setdefault():

data = {}

value = data.setdefault("count", 0)

print(value)
print(data)

Result:

0
{'count': 0}

6. Choosing a lookup method

flowchart TD
    A["Need to get data from a dictionary"] --> B{"Must the key exist?"}
    B -->|"Yes"| C["Use d[key]"]
    B -->|"No"| D{"Does the dictionary need to be initialized?"}
    D -->|"Yes"| E["Use setdefault"]
    D -->|"No"| F["Use get"]
    C --> G["Get the corresponding value"]
    E --> G
    F --> G

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155

    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

III. Methods for Adding to and Updating a Dictionary

A dictionary is a mutable object, so you can add new key-value pairs at any time and also change the value associated with an existing key.

1. Bracket assignment: adding or modifying

This is the most direct way to do it.

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

# Add
user["city"] = "Tokyo"

# Modify
user["age"] = 26

print(user)

Output:

{
    "name": "Alice",
    "age": 26,
    "city": "Tokyo"
}

Its behavior depends on whether the key already exists:

  • Key does not exist: a new key-value pair is added.
  • Key already exists: the original value is updated.

2. update(): batch updates

update() lets you add or modify multiple key-value pairs in one go.

Syntax:

dict.update(other)

Here, other can be:

  • Another dictionary or mapping object.
  • An iterable containing two-element key-value pairs.
  • Keyword arguments.

Example 1: updating with another dictionary.

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

user.update({
    "age": 26,
    "city": "Tokyo"
})

print(user)

Example 2: updating with a sequence of key-value pairs.

user = {
    "name": "Alice"
}

user.update([
    ("age", 25),
    ("city", "Tokyo")
])

print(user)

Example 3: updating with keyword arguments.

config = {
    "host": "localhost",
    "port": 8000
}

config.update(
    port=9000,
    debug=True
)

print(config)

update() modifies the original dictionary in place and returns None.

result = config.update({"timeout": 30})

print(result)  # None

Do not write it like this:

config = config.update({"timeout": 30})

Because this reassigns config to None.

3. Dictionary merge operator: |

Starting with Python 3.9, dictionaries support the | merge operator.

default_config = {
    "host": "localhost",
    "port": 8000
}

custom_config = {
    "port": 9000,
    "debug": True
}

config = default_config | custom_config

print(config)

Output:

{
    "host": "localhost",
    "port": 9000,
    "debug": True
}

Merge rules:

  • Create a new dictionary.
  • Keep all keys from both dictionaries.
  • If a key is duplicated, the value from the right-hand dictionary overrides the value from the left-hand dictionary.
  • Do not modify the original dictionaries involved in the merge.

4. In-place merge operator: |=

Starting with Python 3.9, you can also use |= to merge dictionaries in place.

config = {
    "host": "localhost",
    "port": 8000
}

config |= {
    "port": 9000,
    "debug": True
}

print(config)

|= directly modifies the dictionary on the left.

5. Dictionary unpacking: **

You can use ** to unpack multiple dictionaries into a new dictionary.

default_config = {
    "host": "localhost",
    "port": 8000
}

custom_config = {
    "port": 9000,
    "debug": True
}

config = {
    **default_config,
    **custom_config
}

print(config)

Later keys with the same name override earlier values.

Dictionary unpacking can also be used to construct a new dictionary containing fixed fields and dynamic fields:

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

result = {
    "id": 1001,
    **user,
    "active": True
}

6. Differences between update(), |, |=, and **

Method Creates a new dictionary? Modifies the original dictionary? Version
update() No Yes Since early Python versions
a \| b Yes No Python 3.9+
a \|= b No Yes Python 3.9+
{**a, **b} Yes No Python 3.5+

Recommendations:

  • Update an existing dictionary: use update().
  • Merge while preserving the original dictionaries: use |.
  • Merge in place: use |=.
  • Construct a new dictionary and combine multiple fields: use **.

Note that these operations are usually shallow merges. Internal objects such as nested dictionaries and lists are not automatically deep-copied.

IV. Dictionary Deletion Methods

Dictionaries provide several deletion operations: you can delete a specified key, delete the most recently inserted key-value pair, or clear the entire dictionary.

1. del: Delete a specified key

user = {
    "name": "Alice",
    "age": 25,
    "city": "Tokyo"
}

del user["age"]

print(user)

If the key does not exist, a KeyError is raised.

If you need to check before deleting:

if "age" in user:
    del user["age"]

2. pop(): Delete and return a specified value

pop() deletes the specified key and returns the deleted value.

Syntax:

dict.pop(key, default)

Example:

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

age = user.pop("age")

print(age)
print(user)

Output:

25
{'name': 'Alice'}

If the key does not exist, you can provide a default value:

email = user.pop("email", "未填写")

print(email)

If the key does not exist and no default value is provided, KeyError is raised.

3. popitem(): Remove the Last Inserted Key-Value Pair

user = {
    "name": "Alice",
    "age": 25,
    "city": "Tokyo"
}

item = user.popitem()

print(item)
print(user)

Starting with Python 3.7, popitem() removes the last inserted key-value pair in last-in, first-out order.

The return value is a two-tuple:

(key, value)

If the dictionary is empty, KeyError is raised.

4. clear(): Clear the Dictionary

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

user.clear()

print(user)

Output:

{}

clear() removes all key-value pairs, but does not delete the dictionary variable itself.

5. Comparison of Deletion Methods

Method Action Return Value When the Key Does Not Exist
del d[key] Deletes the specified key None KeyError
d.pop(key) Deletes the specified key and returns the value The removed value KeyError
d.pop(key, default) Deletes the specified key and returns the value Value or default value Returns the default value
d.popitem() Deletes the last inserted item (key, value) KeyError when the dictionary is empty
d.clear() Clears the dictionary None Not applicable

6. How to Choose a Deletion Method

flowchart TD
    A["Need to delete dictionary data"] --> B{"Deletion scope"}
    B -->|"Entire dictionary contents"| C["clear()"]
    B -->|"Specified key"| D{"Need to return the deleted value?"}
    B -->|"Last inserted item"| E["popitem()"]
    D -->|"Yes"| F["pop(key)"]
    D -->|"No"| G["del d[key]"]
    C --> H["Deletion operation complete"]
    E --> H
    F --> H
    G --> H

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155

    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

V. Dictionary Traversal Methods

Traversal is one of the most important operations when using dictionaries.

Python dictionaries support direct traversal, and also support accessing keys, values, and key-value pairs separately through keys(), values(), and items().

1. Traverse the Dictionary Directly

user = {
    "name": "Alice",
    "age": 25,
    "city": "Tokyo"
}

for key in user:
    print(key)

Output:

name
age
city

When you iterate over a dictionary directly, the default is to iterate over its keys.

The following写法 has the same effect as iterating over the dictionary directly:

for key in user.keys():
    print(key)

2. keys(): Iterate Over All Keys

Syntax:

dict.keys()

Example:

user = {
    "name": "Alice",
    "age": 25,
    "city": "Tokyo"
}

for key in user.keys():
    print(key)

keys() returns a dictionary key view (Dictionary View), not a regular list.

You can convert it to a list with list():

keys = list(user.keys())

print(keys)

The key view is linked to the original dictionary and reflects subsequent changes to the dictionary.

user = {
    "name": "Alice"
}

keys = user.keys()

user["age"] = 25

print(keys)

3. values(): Iterate Over All Values

Syntax:

dict.values()

Example:

user = {
    "name": "Alice",
    "age": 25,
    "city": "Tokyo"
}

for value in user.values():
    print(value)

values() returns a dictionary value view.

If you only care about the data content and don't need the corresponding keys, you can use it.

Convert to a list:

values = list(user.values())

print(values)

Note: the value view can contain duplicate values.

scores = {
    "Alice": 90,
    "Bob": 90,
    "Charlie": 85
}

print(list(scores.values()))

4. items(): Iterate Over Key-Value Pairs

items() is one of the most commonly used dictionary iteration methods in real-world development.

Syntax:

dict.items()

Example:

user = {
    "name": "Alice",
    "age": 25,
    "city": "Tokyo"
}

for key, value in user.items():
    print(key, value)

Output:

name Alice
age 25
city Tokyo

items() returns a key-value pair view, and each element can be unpacked into (key, value).

You can also use just one variable:

for item in user.items():
    print(item)

Each item is a two-element tuple.

5. Comparison of keys(), values(), and items()

Method Returns Element Structure Typical Use
keys() All keys A single key When you only need the keys
values() All values A single value When you only need the values
items() All key-value pairs (key, value) When you need both keys and values

All three methods return dynamic view objects:

  • dict_keys
  • dict_values
  • dict_items

They are not lists, but they can be iterated over and converted to lists with list().

6. Iterating Over a Dictionary with enumerate()

enumerate() can attach a counting index to the iteration results.

user = {
    "name": "Alice",
    "age": 25,
    "city": "Tokyo"
}

for index, key in enumerate(user):
    print(index, key)

Output:

0 name
1 age
2 city

You can also start from a specified number:

for index, (key, value) in enumerate(user.items(), start=1):
    print(index, key, value)

Note that enumerate() returns an iteration position count, not an index that actually exists in the dictionary.

7. Using sorted() for Sorted Iteration

Dictionaries preserve insertion order, but if you need to sort by key or value, you can use sorted().

Sort by key:

scores = {
    "Charlie": 85,
    "Alice": 90,
    "Bob": 80
}

for key in sorted(scores):
    print(key, scores[key])

Sort by value:

for key, value in sorted(
    scores.items(),
    key=lambda item: item[1]
):
    print(key, value)

Sort by value from high to low:

for key, value in sorted(
    scores.items(),
    key=lambda item: item[1],
    reverse=True
):
    print(key, value)

If you need a new sorted dictionary:

sorted_scores = dict(
    sorted(
        scores.items(),
        key=lambda item: item[1],
        reverse=True
    )
)

print(sorted_scores)

Note:

  • sorted() returns a list.
  • dict() can reconstruct the sorted key-value pairs into a dictionary.
  • The sorted dictionary still preserves the insertion order from when it was constructed.

8. Typical Ways to Iterate Through a Dictionary

data = {
    "A": 100,
    "B": 200,
    "C": 300
}

# Iterate over keys only
for key in data:
    print(key)

# Iterate over values only
for value in data.values():
    print(value)

# Iterate over keys and values together
for key, value in data.items():
    print(key, value)

# Iterate with an index
for index, (key, value) in enumerate(data.items(), start=1):
    print(index, key, value)

VI. Dictionary View Objects and Iteration Considerations

keys(), values(), and items() return dynamic view objects, not ordinary lists.

Understanding this can help you avoid some common issues.

1. View Objects Reflect Changes to the Dictionary

data = {
    "a": 1,
    "b": 2
}

keys = data.keys()
values = data.values()
items = data.items()

data["c"] = 3

print(keys)
print(values)
print(items)

All three views reflect the newly added key-value pair.

This means they are not snapshots of the data at creation time.

2. Differences Between View Objects and Lists

Aspect Dictionary View List
Dynamically linked to the original dictionary Yes No
Supports iteration Yes Yes
Supports indexing Does not support normal sequence indexing Yes
Can be converted to a list Yes Is a list itself
Automatically copies data No A new list is constructed when the list is created

When you need a fixed snapshot, you can use:

keys_snapshot = list(data.keys())

If you modify the original dictionary afterward, this list will not change.

3. Do Not Add or Delete Keys Arbitrarily During Iteration

The following code is risky:

data = {
    "a": 1,
    "b": 2,
    "c": 3
}

for key in data:
    if key == "b":
        del data[key]

This may trigger:

RuntimeError: dictionary changed size during iteration

The reason is that the dictionary structure was modified during iteration.

Correct approach one: first collect the keys that need to be deleted.

data = {
    "a": 1,
    "b": 2,
    "c": 3
}

keys_to_delete = [
    key
    for key, value in data.items()
    if value < 3
]

for key in keys_to_delete:
    del data[key]

print(data)

Correct approach two: iterate over a copy.

for key in list(data):
    if data[key] < 3:
        del data[key]

Correct approach three: build a new dictionary.

filtered = {
    key: value
    for key, value in data.items()
    if value >= 3
}

4. Modifying existing values during iteration

If you do not change the dictionary's key set or size, modifying the values associated with existing keys is generally fine:

scores = {
    "Alice": 80,
    "Bob": 70,
    "Charlie": 90
}

for name in scores:
    scores[name] += 10

print(scores)

However, avoid making the iteration logic depend on the modified data, which creates hard-to-understand side effects.

In engineering practice, if complex data transformation is needed, building a new dictionary is usually recommended.

VII. Other Common Dictionary Methods

In addition to querying, updating, deleting, and iterating, dictionaries also provide some auxiliary methods.

1. copy(): shallow copy

copy() is used to create a shallow copy of a dictionary.

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

new_user = user.copy()

new_user["age"] = 30

print(user)
print(new_user)

Modifying a top-level value of the new dictionary does not affect the original dictionary.

But if nested objects are involved, the inner objects still share references.

user = {
    "name": "Alice",
    "scores": [90, 95]
}

new_user = user.copy()

new_user["scores"].append(100)

print(user["scores"])
print(new_user["scores"])

The scores in the two dictionaries actually reference the same list.

If a deep copy is needed, you can use:

import copy

new_user = copy.deepcopy(user)

2. fromkeys(): creating a dictionary from keys

fromkeys() can create a new dictionary from the keys in an iterable, and set the same initial value for all keys.

Syntax:

dict.fromkeys(iterable, value=None)

Example: