0

I want to change just Keys (not Values) in a Dictionary in Python. Is there any way to do that?

0

1 Answer 1

2

You can pop the value of the old key and reassign:

d = {'A': 1, 'B': 2, 'C': 3}
d['b'] = d.pop('B')

print(d)
# {'A': 1, 'C': 3, 'b': 2}

Note that this won't maintain the order of the keys (python 3.6+). The renamed key will be instead at the end.

maintaining order

If order is important you need to create a new dictionary

d = {'A': 1, 'B': 2, 'C': 3}

rename = {'B': 'b', 'A': 'a'}

d = {rename.get(k, k): v for k,v in d.items()}

print(d)
# {'a': 1, 'b': 2, 'C': 3}

in place modification while maintaining order

If you want to modify the dictionary in place (i.e. not creating a new object), you need to pop and reinsert all keys in order:

d = {'A': 1, 'B': 2, 'C': 3}
rename = {'B': 'b', 'A': 'a'}

keys = list(d)

for k in keys:
    d[rename.get(k, k)] = d.pop(k)

print(d)
{'a': 1, 'b': 2, 'C': 3}
Sign up to request clarification or add additional context in comments.

Comments

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.