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

Kent Johnson kent37 at tds.net
Tue Oct 2 19:00:39 CEST 2007


GTXY20 wrote:
> Here's an interesting question:
> 
> Can I use the transFn function to remove items in the value list.
> 
> Can this be done by simple assigning the current value a value of null
> in the translate file?

No, that will make the translated value be None (I guess that is what 
you mean by null). You could then filter for these, for example

     for key, value in Data.items():
        Data[key] = [ transDict.get(i, i) for i in value if 
transDict.get(i, i) is not None]

If you want to avoid double-fetching from transDict (if Data is huge 
this might matter) then you could write out the loop or possibly use 
something like
   Data[key] = [ x for x in (transDict.get(i, i) for i in value) if x is 
not None]

which makes an intermediate generator and filters that.

Kent

> 
> M.
> 
> 
> 
> On 10/2/07, GTXY20 <gtxy20 at gmail.com> wrote:
>> I adjusted so that I get the following so if I do not need to translate a
>> dictionary I do not call the function transFn:
>>
>> def transFn(translatefile):
>>     transfile = open(translatefile, 'r')
>>     records = transfile.read()
>>     transfile.close()
>>     lines = records.split()
>>     transDict = {}
>>     for line in lines:
>>         key, value = line.split(',')
>>         transDict[key] = value
>>
>>     for key, value in Data.items():
>>       Data[key] = [ transDict.get(i, i) for i in value ]



More information about the Tutor mailing list