Adding a prefix to each key in a dictionary is a common task when manipulating or organizing data. For example, we might want to indicate the source of the keys or make them more descriptive. Let's explore multiple methods to achieve this in Python.
Using Dictionary Comprehension
We can use dictionary comprehension to efficiently add a prefix to each key in the dictionary.
# Initialize a dictionary
a = {"name": "Nikki", "age": 25, "city": "New York"}
# Add prefix to each key
b = {f"prefix_{k}": v for k, v in a.items()}
# Print the updated dictionary
print(b)
Output
{'prefix_name': 'Nikki', 'prefix_age': 25, 'prefix_city': 'New York'}
Explanation:
- The dictionary comprehension loops over the key-value pairs using
a.items(). - For each key
k, the prefix"prefix_"is added using an f-string. - The result is a new dictionary with updated keys and the original values.
Let's explore some more ways and see how we can add prefix to each key name in dictionary.
Using map() for keys
map() function can be used with a lambda function to apply a transformation to the keys.
# Initialize a dictionary
a = {"name": "Nikki", "age": 25, "city": "New York"}
# Add prefix to each key
b = dict(map(lambda x: (f"prefix_{x[0]}", x[1]), a.items()))
# Print the updated dictionary
print(b)
Output
{'prefix_name': 'Nikki', 'prefix_age': 25, 'prefix_city': 'New York'}
Explanation:
map()function applies the lambda function to each key-value pair ina.items().- lambda function modifies the key by adding the prefix while keeping the value unchanged.
dict()function is used to convert the mapped items back into a dictionary.
Using for Loop
A traditional for loop can also be used to create a new dictionary with prefixed keys.
# Initialize a dictionary
a = {"name": "Nikki", "age": 25, "city": "New York"}
# Initialize an empty dictionary
b = {}
# Add prefix to each key
for k, v in a.items():
b[f"prefix_{k}"] = v
# Print the updated dictionary
print(b)
Output
{'prefix_name': 'Nikki', 'prefix_age': 25, 'prefix_city': 'New York'}
Explanation:
- An empty dictionary
bis initialized to store the new key-value pairs. - The
forloop iterates overa.items(), and the prefix is added to each key using an f-string. - Each updated key-value pair is added to the new dictionary.