Change key name in dict python

How to rename keys in a python dictionary of dictionaries with arbitrary depth

I have a dictionary which contains dictionaries, which may in turn contain dictionaries ad infinitum. I want to change every key in all of the dictionaries, with the exception of the keys which map to one of the nested dictionaries. I understand that the keys are immutable, what I want to do something like this:

layer[item + '_addition'] = layer.pop(item) 
def alterKeys(item, layer=topLevelDict): if isinstance(item, dict): for i in item: alterKeys(item[i], item) else: layer[item + '_addition'] = layer.pop(item) 

This doesn’t work, as it will continually travel recursively down the tree till the last line tries to pop a value from the dict, instead of a key, which raises a KeyError. I know I’m close to a solution, but I’ve been thinking about this for a few minutes and I can’t seem to figure it out.

3 Answers 3

While writing this question, I figured it out. I figured I’d post this in case someone else has the same question at some point.

def alterKeys(item, layer=topLevelDict, key=None): if isinstance(item, dict): for k, v in item.items(): alterKeys(v, item, k) elif isinstance(key, str): layerChange key name in dict python = layer.pop(key) 

If anyone has a more elegant or otherwise better solution, I’d love to see it. I just tested this script out by running a json file through it and it renamed every key that wasn’t mapping to a dictionary, which is exactly what I wanted.

Читайте также:  Rest api python подключение

If I wanted every key to be renamed, including those which mapped to the nested dictionaries, I could use this code instead:

def alterKeys(item, layer=topLevelDict, key=None): if isinstance(item, dict): for k, v in item.items(): alterKeys(v, item, k) if isinstance(key, str): layerChange key name in dict python = layer.pop(key) 

If you’re using python2, remember to use .iteritems() instead of .items(), and use isinstance(key, basestring) instead of isinstance(key, str).

Источник

Change dictionary key in Python

This article explains how to change the key name in a dictionary ( dict ) in Python.

To change the value instead of the key, just specify the key and assign a new value. See the following article for details.

Add a new item and then remove the old one

As dict does not provide a method to rename the key directly, you need to add a new item with the new key and the original value, and then remove the old item.

For more information on how to remove an item from the dictionary, see the following article.

With the del statement

If you use the del statement, you can achieve this as follows:

d = 'k1': 1, 'k2': 2, 'k3': 3> d['k10'] = d['k1'] del d['k1'] print(d) # 

With the pop() method

The pop() method can be used to remove an item and get its value simultaneously.

d = 'k1': 1, 'k2': 2, 'k3': 3> print(d.pop('k1')) # 1 print(d) # 

Using pop() is simpler than using del because it allows you to remove an item and get its value in a single step.

d = 'k1': 1, 'k2': 2, 'k3': 3> d['k10'] = d.pop('k1') print(d) # 

Note that, by default, an error occurs if a non-existent key is specified as the first argument of pop() .

d = 'k1': 1, 'k2': 2, 'k3': 3> # print(d.pop('k10')) # KeyError: 'k10' 

If the second argument of pop() is specified, it returns the value without error. The original dictionary object remains unchanged.

print(d.pop('k10', None)) # None print(d) # 

This can be used to set a default value if you try to change a key that does not exist. It is used in the function described next.

Define a function to change the key in a dictionary

Here are some examples of functions to change the key in a dictionary.

If the old key does not exist, add a new item

For example, you can define the following function using pop() .

The first argument is the target dictionary, the second is the old key, and the third is the new key.

def change_dict_key(d, old_key, new_key, default_value=None): d[new_key] = d.pop(old_key, default_value) d = 'k1': 1, 'k2': 2, 'k3': 3> change_dict_key(d, 'k1', 'k10') print(d) # 

If a non-existent key is specified as the old key, a new item is added using the key with the value specified in the fourth argument ( None by default).

d = 'k1': 1, 'k2': 2, 'k3': 3> change_dict_key(d, 'k10', 'k100') print(d) # d = 'k1': 1, 'k2': 2, 'k3': 3> change_dict_key(d, 'k10', 'k100', 100) print(d) # 

If an existing key is specified as the third argument (new key), the value of the existing key is overwritten.

d = 'k1': 1, 'k2': 2, 'k3': 3> change_dict_key(d, 'k1', 'k2') print(d) # 

If you want to keep the original value when specifying an existing key as a new key, use the setdefault() method.

def change_dict_key_setdefault(d, old_key, new_key, default_value=None): d.setdefault(new_key, d.pop(old_key, default_value)) d = 'k1': 1, 'k2': 2, 'k3': 3> change_dict_key_setdefault(d, 'k1', 'k2') print(d) # 

If the new key is not an existing key, the behavior is the same as the first function.

d = 'k1': 1, 'k2': 2, 'k3': 3> change_dict_key_setdefault(d, 'k1', 'k10') print(d) # d = 'k1': 1, 'k2': 2, 'k3': 3> change_dict_key_setdefault(d, 'k10', 'k100') print(d) # 

If the old key does not exist, do nothing

If you want the function to do nothing when the specified key does not exist, use the in operator.

def change_dict_key_exist(d, old_key, new_key): if old_key in d: d[new_key] = d.pop(old_key) d = 'k1': 1, 'k2': 2, 'k3': 3> change_dict_key_exist(d, 'k1', 'k10') print(d) # d = 'k1': 1, 'k2': 2, 'k3': 3> change_dict_key_exist(d, 'k10', 'k100') print(d) # 

If an existing key is specified as the third argument (new key), the value of the existing key is overwritten.

d = 'k1': 1, 'k2': 2, 'k3': 3> change_dict_key_exist(d, 'k1', 'k2') print(d) # 

As in the previous example, if you want to keep the original value when specifying an existing key as a new key, use the setdefault() method.

def change_dict_key_exist_setdefault(d, old_key, new_key): if old_key in d: d.setdefault(new_key, d.pop(old_key)) d = 'k1': 1, 'k2': 2, 'k3': 3> change_dict_key_exist_setdefault(d, 'k1', 'k2') print(d) # 

Источник

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 –

  1. Remove the old key to value pair from the dictionary.
  2. 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 –

# rename key in dictionary my_dict[new_key] = my_dict.pop(old_key)

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

# create a dictionary capital_info = < "India": "New Delhi", "USA": "Washington DC", "UK": "London" ># rename key in dictionary capital_info["United States of America"] = capital_info.pop("USA") # display the dictionary print(capital_info)

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.

# rename key in dictionary capital_info["United Kingdom"] = capital_info.pop("UK") # display the dictionary print(capital_info)

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.

# create a dictionary capital_info = < "India": "New Delhi", "USA": "Washington DC", "UK": "London" ># rename key in dictionary capital_info["United States of America"] = capital_info["USA"] del capital_info["USA"] # display the dictionary print(capital_info)

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.

Author

Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts

Источник

Оцените статью