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

Kent Johnson kent37 at tds.net
Tue Oct 2 21:47:06 CEST 2007


GTXY20 wrote:
> 
> I have the transFn function as follows:
> 
> 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] = [ x for x in (transDict.get (i, i) for i in value) if 
> x is not None]
> 
> my original data is:
> 
> data = {'1': ['a', 'b', 'c'], '3': ['a', 'b', 'c'], '2': ['a', 'b', 
> 'c'], '4': ['a', 'c']}
> 
> my transDict is:
> 
> transDict = {'a': '1', 'b': '2'}
> 
> However when I run transFn my data is:
> 
> data = {'1': ['1', '2', 'c'], '3': ['1', '2', 'c'], '2': ['1', '2', 
> 'c'], '4': ['1', 'c']}
> 
> I was expecting:
> 
> {'1': ['1', '2'], '3': ['1', '2'], '2': ['1', '2'], '4': ['1']}

Well you said you would assign null to the value in transDict and you 
did not do that.

I fear I am giving you too much code and not enough understanding. You 
should be figuring some of this stuff out yourself. Look at the docs for 
dict.get() and see if you can change your code to do what you want.

Kent


More information about the Tutor mailing list