@
@
@chistya2017-07-05 15:50:01
Python
@chistya, 2017-07-05 15:50:01

How to change key names in a python dictionary?

Good afternoon.
There is a dictionary: It is necessary to replace the names of some keys in it. For example:
d1 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}

d2 = {'one':'a', 2:'b', 3:'c', 'four':'d', 'five':'e'}

How it is more correct to make it? The variant with a bunch of if looks cumbersome:
for i in d1:
  if i == 1:
    d2['one'] = d1[i]
  ...
  else:
    d2[i] = d1[i]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Kuzmichev, 2017-07-05
_

There is no way to simply rename a key in python dictionaries.
An example of assigning a value to a new key from the old key, with the removal of the old key.
If your question is how to build the replacement algorithm itself, then I can suggest the following:

# словарь
d1 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}
# словарь замен: ключ - исходный ключ из d1, значение - на какой ключ его меняем
replacements = {1: 'one', 4: 'four', 5: 'five'}

for i in d1:
    if i in replacements:
        d1[replacements[i]] = d1.pop(i)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question