Reputation: 447
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],
}
Upvotes: 3
Views: 8327
Reputation: 6234
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.
Upvotes: 5
Reputation: 610
You can not change a key in a dictionary. The only way to replace it is to create a new dictionary or, add a new key and delete the old key.
The code below uses dictionary comprehension to create a dictionary.
mydictionary = {
'item_1': [7,19],
'item_2': [0,3],
'item_3': [54,191],
'item_4': [41,43],
}
mydictionary = {f"object_{index}": mydictionary[value] for index, value in enumerate(mydictionary, 1)}
output:
{'object_1': [7, 19], 'object_2': [0, 3], 'object_3': [54, 191], 'object_4': [41, 43]}
Upvotes: 0
Reputation: 206
You can't change the keys in a dictionary, so you will need to create a new dictionary. The most concise way to do this is probably comprehensions. First we, need to replace every string "item" with "object" in our old keys, then create a new dictionary with the same values. This should do it:
# Get keys
oldkeys = list(mydictionary.keys())
# Change "item" to "object"
newkeys = [s.replace('item', 'object') for s in oldkeys]
# Get values
vals = list(mydictionary.values())
# Create new dictionary by iterating over both newkeys and vals
newdictionary = {k: v for k, v in zip(newkeys, vals)}
newdictionary
now looks like this:
{'object_1': [7, 19], 'object_2': [0, 3], 'object_3': [54, 191], 'object_4': [41, 43]}
Note that you could combine this into one comprehension with mydictionary.items()
to get the key and value pairs as a tuple.
Upvotes: 2