Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the keys of a dictionary?

Let's say I have a pretty complex dictionary.

{'fruit':'orange','colors':{'dark':4,'light':5}} 

Anyway, my objective is to scan every key in this complex multi-level dictionary. Then, append "abc" to the end of each key.

So that it will be:

{'fruitabc':'orange','colorsabc':{'darkabc':4,'lightabc':5}} 

How would you do that?

like image 933
TIMEX Avatar asked Feb 06 '10 14:02

TIMEX


People also ask

Can you change the key of a dictionary?

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.

How do I rename a dictionary 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.


2 Answers

Keys cannot be changed. You will need to add a new key with the modified value then remove the old one, or create a new dict with a dict comprehension or the like.

like image 119
Ignacio Vazquez-Abrams Avatar answered Oct 02 '22 20:10

Ignacio Vazquez-Abrams


For example like this:

def appendabc(somedict):     return dict(map(lambda (key, value): (str(key)+"abc", value), somedict.items()))  def transform(multilevelDict):     new = appendabc(multilevelDict)      for key, value in new.items():         if isinstance(value, dict):             new[key] = transform(value)      return new  print transform({1:2, "bam":4, 33:{3:4, 5:7}}) 

This will append "abc" to each key in the dictionary and any value that is a dictionary.

EDIT: There's also a really cool Python 3 version, check it out:

def transform(multilevelDict):     return {str(key)+"abc" : (transform(value) if isinstance(value, dict) else value) for key, value in multilevelDict.items()}  print(transform({1:2, "bam":4, 33:{3:4, 5:7}})) 
like image 21
AndiDog Avatar answered Oct 02 '22 20:10

AndiDog