Skip to content

How to Add a Prefix to Dictionary Keys in Python

Learn Python's most efficient ways to add prefixes to dictionary keys using dictionary comprehensions, loops, or recursive functions for nested structures.

Adding prefixes to dictionary keys is a common task when preparing data for APIs, merging datasets, or avoiding key collisions. Python offers several approaches, with dictionary comprehensions being the most idiomatic.

Using Dictionary Comprehension

The most Pythonic approach rebuilds the dictionary with modified keys in a single expression:

data = {"name": "Alice", "age": 30, "city": "Boston"}

prefixed = {f"user_{key}": value for key, value in data.items()}

print(prefixed)

Adding Suffixes or Other Transformations

The same pattern works for any key transformation:

data = {"name": "Alice", "email": "alice@example.com"}

suffixed = {f"{k}_field": v for k, v in data.items()}
print(suffixed)

uppercased = {k.upper(): v for k, v in data.items()}
print(uppercased)

transformed = {f"USER_{k.upper()}": v for k, v in data.items()}
print(transformed)

Output:

{'name_field': 'Alice', 'email_field': 'alice@example.com'}
{'NAME': 'Alice', 'EMAIL': 'alice@example.com'}
{'USER_NAME': 'Alice', 'USER_EMAIL': 'alice@example.com'}

Conditional Prefixing

Apply prefixes selectively based on conditions:

data = {"id": 1, "name": "Alice", "id_type": "user"}

result = {
    (f"user_{k}" if not k.startswith("id") else k): v 
    for k, v in data.items()
}
print(result)

Output:

{'id': 1, 'user_name': 'Alice', 'id_type': 'user'}

Working with Nested Dictionaries

For nested structures, use recursion:

def add_prefix_recursive(data, prefix):
    """Add prefix to all keys in nested dictionary."""
    if not isinstance(data, dict):
        return data
    
    return {
        f"{prefix}{key}": add_prefix_recursive(value, prefix)
        for key, value in data.items()
    }

nested = {
    "user": {
        "name": "Alice",
        "address": {
            "city": "Boston",
            "zip": "02101"
        }
    }
}

result = add_prefix_recursive(nested, "app_")
print(result)

Output:

{'app_user': {'app_name': 'Alice', 'app_address': {'app_city': 'Boston', 'app_zip': '02101'}}}

Using a Standard Loop

When you need more control or debugging visibility:

data = {"name": "Alice", "age": 30}

new_data = {}
for key, value in data.items():
    new_key = f"user_{key}"
    new_data[new_key] = value

print(new_data)

Output:

{'user_name': 'Alice', 'user_age': 30}

Creating a Reusable Function

Encapsulate the logic for repeated use:

def prefix_keys(dictionary: dict, prefix: str) -> dict:
    """Return new dictionary with prefixed keys."""
    return {f"{prefix}{k}": v for k, v in dictionary.items()}

def suffix_keys(dictionary: dict, suffix: str) -> dict:
    """Return new dictionary with suffixed keys."""
    return {f"{k}{suffix}": v for k, v in dictionary.items()}

user_data = {"name": "Alice", "role": "admin"}
print(prefix_keys(user_data, "user_"))

Output:

{'user_name': 'Alice', 'user_role': 'admin'

Method Comparison

Method Readability Performance Use Case
Dict comprehension ⭐⭐⭐⭐⭐ ⚡ Fast Standard choice
For loop ⭐⭐⭐ Slightly slower Complex logic, debugging
map() with dict() ⭐⭐ Similar Functional programming style

Summary

Dictionary comprehension {f"prefix_{k}": v for k, v in d.items()} is the standard idiom for transforming dictionary keys in Python. It's concise, readable, and efficient. For nested dictionaries, combine this pattern with recursion. Always create a new dictionary rather than modifying keys during iteration.

Navigation