Как изменить имена ключей в словаре python?
Добрый день.
Есть словарь:
d1 = <1:'a', 2:'b', 3:'c', 4:'d', 5:'e'>
В нем необходимо заменить имена некоторых ключей. Например:
Как это правильнее сделать? Вариант с кучей if выглядит громоздким:
- Вопрос задан более трёх лет назад
- 18185 просмотров
- Вконтакте
Возможности просто переименовать ключ в словарях питона нет.
Пример присваивания новому ключу значение из старого ключа, с удалением старого ключа.
dictionary[new_key] = dictionary.pop(old_key)
Если же вопрос ваш в том, как построить сам алгоритм замены, то могу предложить следующий:
Rename a Key in a Python Dictionary
When working with dictionaries it might happen that you need to modify the key name without changing its value for a particular key-value pair. In this tutorial, we will look at how to rename a key in a Python dictionary with the help of some examples.
Can we rename a key in a dictionary in Python?
There is no direct way of renaming a key in a Python dictionary. But, you can achieve the end result using the following steps –
- Remove the old key to value pair from the dictionary.
- Add the new key to value pair to the dictionary.
The order of the above steps is not important so long as you use the same value for the new key.
How to rename a key in a Python dictionary?
To rename a Python dictionary key, use the dictionary pop() function to remove the old key from the dictionary and return its value. And then add the new key with the same value to the dictionary.
The following is the syntax –
Let’s now look at some examples of using the above syntax.
We have a dictionary containing countries to their capital cities mapping. Let’s rename the key “USA” to “United States of America”.
Here we are removing the old key, “USA” and returning its value using the pop() function and then assigning the returned value to the new key, “United States of America”. You can see that instead of “USA” we have “United States of America” in the dictionary.
Let’s look at another example.
Here we rename “UK” to “United Kingdom”.
Note that we’re not really renaming here. We are removing the old key and then adding the new key with the same value thereby getting the same end result as a rename operation (if it were available).
Using del keyword
Alternatively, you can use the del keyword instead of the pop() function to remove a key from a dictionary. Check out this tutorial on the differences between the two.
We get the same result as above.
Note that if the key is not present in the dictionary, removing using the del keyword will result in a KeyError .
You might also be interested in –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Change the name of a key in dictionary
How do I change the key of an entry in a Python dictionary?
23 Answers 23
Easily done in 2 steps:
which will raise KeyError if dictionary[old_key] is undefined. Note that this will delete dictionary[old_key] .
if you want to change all the keys:
if you want to change single key: You can go with any of the above suggestion.
In python 2.7 and higher, you can use dictionary comprehension: This is an example I encountered while reading a CSV using a DictReader. The user had suffixed all the column names with ‘:’
to get rid of the trailing ‘:’ in the keys:
![]()
suppose that we want to change the keys to the list elements p=[‘a’ , ‘b’]. the following code will do:
![]()
Since keys are what dictionaries use to lookup values, you can’t really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value. Several of the other answers illustrate different ways this can be accomplished.
![]()
No direct way to do this, but you can delete-then-assign
or do mass key changes:
If you have a complex dict, it means there is a dict or list within the dict:
![]()
You can use iff/else dictionary comprehension. This method allows you to replace an arbitrary number of keys in one line AND does not require you to change all of them.
To convert all the keys in the dictionary
Suppose this is your dictionary:
To convert all the dashes to underscores in the sample dictionary key:
this function gets a dict, and another dict specifying how to rename keys; it returns a new dict, with renamed keys:
![]()
In case of changing all the keys at once. Here I am stemming the keys.
This will lowercase all your dict keys. Even if you have nested dict or lists. You can do something similar to apply other transformations.
![]()
Replacing spaces in dict keys with underscores, I use this simple route .
Or just dictionary.pop(k) Note ‘e r r’, which can be any string, would become the new value if the key is not in the dictionary to be able to replace it, which can’t happen here. The argument is optional, in other similar code where KeyError might be hit, that added arg avoids it and yet can create a new key with that ‘e r r’ or whatever you set it to as the value.
.copy() avoids . dictionary changed size during iteration.
.keys() not needed, k is each key, k stands for key in my head.
What’s the one-liner for the loop above?
![]()
I just had to help my wife do something like those for a python class, so I made this code to show her how to do it. Just like the title says, it only replaces a key name. It’s very rare that you have to replace just a key name, and keep the order of the dictionary intact but figured I’d share anyway since this post is what Goggle returns when you search for it even though it’s a very old thread.
You can associate the same value with many keys, or just remove a key and re-add a new key with the same value.
For example, if you have keys->values:
there’s no reason you can’t add purple->2 or remove red->1 and add orange->1
Method if anyone wants to replace all occurrences of the key in a multi-level dictionary.
Function checks if the dictionary has a specific key and then iterates over sub-dictionaries and invokes the function recursively:
![]()
An example of complete solution
Declare a json file which contains mapping you want
Create this function to format a dict with your mapping
![]()
Be aware of the position of pop:
Put the key you want to delete after pop()
orig_dict[‘AAAAA’] = orig_dict.pop(‘A’)
I wrote this function below where you can change the name of a current key name to a new one.
Assuming a JSON you can call it and rename it by the following line:
With pandas you can have something like this,
![]()
For the keeping of order case (the other one is trivial, remove old and add new one) efficiently, avoiding the ordered-dictionary needing reconstruction (at least partially), I’ve put together a class (OrderedDictX) that extends OrderedDict and allows you to do key changes efficiently, i.e. in O(1) complexity. The implementation can also be adjusted for the now-ordered built-in dict class.
It uses 2 extra dictionaries to remap the changed keys ("external" — i.e. as they appear externally to the user) to the ones in the underlying OrderedDict ("internal") — the dictionaries will only hold keys that were changed so as long as no key changing is done they will be empty.
As expected, the splicing method is extremely slow (didn’t expect it to be that much slower either though) and uses a lot of memory, and the O(N) Raymond solution is also slower, 17X times in this example.
Of course, this solution being O(1), compared to the O(N) OrderedDictRaymond the time difference becomes much more apparent as the dictionary size increases, e.g. for 5 times more elements (100000), the O(N) is now 100X slower:
Here’s the code, please comment if you see issues or have improvements to propose as this might still be error-prone.
Обновление словаря в Python
В этом руководстве мы узнаем, как обновить словарь в Python.
Вы уже знаете, что мы можем получить доступ к парам ключ:значение (key:value) словаря в Python, используя ключ в качестве индекса со ссылкой на словарь. Таким же образом вы можете присвоить значение этому ключевому индексу в словаре, чтобы обновить значение пары ключ:значение в этом словаре.
- обновить значение в паре ключ:значение словаря;
- добавить новую пару ключ:значение в словарь;
- Удалить пару ключ:значение из словаря.
Мы рассмотрим каждый из вышеупомянутых вариантов на примерах.
Как обновить значение key:value?
Чтобы обновить значение в словаре, соответствующем ключу, все, что вам нужно сделать, это присвоить значение ссылке на индексированный ключом словарь.
В следующей программе мы обновляем значение в словаре myDict для ключа foo.
Как добавить новую пару key:value?
Чтобы добавить новую пару ключ:значение в dictionary, вы должны присвоить значение ссылке на словарь, индексированный по ключу.
В следующей программе мы добавляем новую пару key:value ‘moo’: 85 в словарь myDict.
Как удалить пару key:value?
Чтобы удалить пару ключ:значение в dictionary, вы можете использовать ключевое слово del со словарем [ключ], как показано в следующей программе.