Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace dynamically replace keys of a dictionary in Python?

I am trying to replace the item with object for the keys in a Python dictionary. I was wondering if re would be required. Or if I can use the replace function? How would I go about doing this?

What I have:

mydictionary = {
    'item_1': [7,19],
    'item_2': [0,3],
    'item_3': [54,191],
    'item_4': [41,43],
}

What I want:

mydictionary = {
    'object_1': [7,19],
    'object_2': [0,3],
    'object_3': [54,191],
    'object_4': [41,43],
}
like image 717
tkxgoogle Avatar asked Sep 13 '25 16:09

tkxgoogle


1 Answers

mydictionary = {
    key.replace("item", "object"): value for key, value in mydictionary.items()
}

The syntax uses dictionary comprehension to create a new dictionary based on the old dictionary but with a modification in old dictionary keys.
Also re module could be used instead of the string replace method but since there is no regular expression/pattern involved re module will only complicate the code.

like image 89
Vishal Singh Avatar answered Sep 16 '25 06:09

Vishal Singh