[Tutor] Update values stored as a list in a dictionary with values from another dictionary
GTXY20
gtxy20 at gmail.com
Tue Oct 2 21:42:00 CEST 2007
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']}
I will see if I can work with a remove command??
M.
On 10/2/07, Kent Johnson <kent37 at tds.net> wrote:
>
> 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 ]
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071002/814dbc24/attachment.htm
More information about the Tutor
mailing list