4

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],
}
1
  • there's a green "accept" arrow in the most upvoted answer: it's waiting for you Commented May 21, 2024 at 17:38

3 Answers 3

5
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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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

1 Comment

This will work only if the OP uses Python 3.7 or newer, and if the items insertion order is in ascending. Insert item_2 before item_1 and this will produce the wrong results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.