Skip to main content

How to Add a Prefix to Dictionary Keys in Python

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)
# Output: {'user_name': 'Alice', 'user_age': 30, 'user_city': 'Boston'}
note

This creates a new dictionary in O(n) time with clean, readable syntax.

Adding Suffixes or Other Transformations

The same pattern works for any key transformation:

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

# Add suffix
suffixed = {f"{k}_field": v for k, v in data.items()}
print(suffixed)
# Output: {'name_field': 'Alice', 'email_field': 'alice@example.com'}

# Uppercase keys
uppercased = {k.upper(): v for k, v in data.items()}
print(uppercased)
# Output: {'NAME': 'Alice', 'EMAIL': 'alice@example.com'}

# Multiple transformations
transformed = {f"USER_{k.upper()}": v for k, v in data.items()}
print(transformed)
# Output: {'USER_NAME': 'Alice', 'USER_EMAIL': 'alice@example.com'}

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"}

# Only prefix keys that don't already start with 'id'
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'}
tip

For complex conditions, extract the logic into a helper function for better readability:

def transform_key(key):
if key.startswith("id"):
return key
return f"user_{key}"

result = {transform_key(k): v for k, v in data.items()}

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}
warning

Never modify dictionary keys while iterating over it. This raises a RuntimeError. Always create a new dictionary or iterate over a copy of the keys.

# ❌ This will fail
for key in data:
data[f"user_{key}"] = data.pop(key) # RuntimeError

# ✅ Safe alternative using list() to copy keys
for key in list(data.keys()):
data[f"user_{key}"] = data.pop(key)

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()}

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

Output:

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

Method Comparison

MethodReadabilityPerformanceUse Case
Dict comprehension⭐⭐⭐⭐⭐⚡ FastStandard choice
For loop⭐⭐⭐Slightly slowerComplex logic, debugging
map() with dict()⭐⭐SimilarFunctional 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.