Merging two lists of data (Pythonic way)
Paul Rubin
http
Thu Feb 16 16:15:59 EST 2006
"SMB" <sean at buildingonline.com> writes:
> What I am doing is looking for a pythonic way to parse the LIST2 "code"
> values and make appropriate changes to to each dictionary if the "code"
> value is the first element of a list in LIST1.
>
> The final result may look like this given that the change is adding a new
> key/value of "VERIFIED"/1 for the matches.
Untested:
from sets import Set
vvals = Set(a[0] for a in LIST1) # get all the List1 first elt. values
for d in LIST2:
if d['code'] in vvals:
d['VERIFIED'] = 1
> I know I could do this with two for loops, but am looking for a better
> solution maybe involving list comprehension.
I think if list1 is potentially long, the main thing is to avoid n**2
running time, which means use a set or dict to do the lookups, like
above.
More information about the Python-list
mailing list