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],
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With