Converting the keys of a dictionary from numeric to string

Peter Otten __peter__ at web.de
Thu Oct 20 03:49:37 EDT 2016


pozz wrote:

> I have a dictionary where the keys are numbers:
> 
> mydict = { 1: 1000, 2: 1500, 3: 100 }
> 
> I would like to convert keys from number to string representation:
> 
> mydict = { "apples": 1000, "nuts": 1500, "tables": 100 }
> 
> Of course, somewhere I have the association between key-numbers and
> key-strings, maybe in another dictionary:
> 
> keydict = { 1: "apples", 2: "nuts", 3; "tables" }
> 
> How could I make the conversion? My solution:
> 
> keydict = { 1: "Joseph", 2: "Michael", 3: "John" }
> mydict = { 1: 1000, 2: 2000, 3: 3000 }
> newdict = {}
> for k in mydict.keys():
>     newdict.update({keydict[k]: mydict[k]})
> print(newdict)

This is the correct approach. You can spell it more elegantly (see Paul's 
answer), but

> I tried changing just mydict (without creating newdict), without success.

changing such a dict in place is hardly ever done by experienced Python 
programmers.

assert len(keydict) == len(mydict)
for k, v in keydict.items():
    mydict[v] = mydict.pop(k)

The code is less clear than

mydict = {keydict[k]: v for k, v in mydict.items()}

and you run the risk of ending up with corrupted data when you encounter a 
missing key halfway through the iteration.





More information about the Python-list mailing list