[Tutor] Update values stored as a list in a dictionary with values from another dictionary

Kent Johnson kent37 at tds.net
Tue Oct 2 13:24:53 CEST 2007


John Fouhy wrote:
> You could use the map function...
> 
> Let's say we have something like:
> 
> transDict = { 'a':1, 'b':2, 'c':3 }
> 
> We could define a function that mirrors this:
> 
> def transFn(c):
>     try:
>         return transDict[c]
>     except KeyError:
>         return c

This could be written more simply as
   return transDict.get(c, c)

> Then if you have your data:
> 
> data = { 1:('a','b','c'), 2:('a','c'), 3:('b','c'), 4:('a','d')}
> 
> You can translate it as:
> 
> for key in data.keys():
>     data[key] = map(transFn, data[key])

I would use a list comprehension and dict.get():

for key, value in data.items():
   data[key] = [ transDict.get(i, i) for i in value ]

Kent


More information about the Tutor mailing list