Merging two lists of data (Pythonic way)

Lonnie Princehouse finite.automaton at gmail.com
Thu Feb 16 16:21:30 EST 2006


You might consider writing two classes to represent the values in list1
and list2.  It might be more Pythonic than sloshing around all of those
lists and dictionaries.

But as it is, it looks like you want to find matching pairs of lists
and dictionaries from list1 and list2, respectively:

# index dictionaries from LIST2 by 'code' element.
# (assumption: no two dicts have the same "code" value)
lookup_table = dict( [(d['code'], d) for list in LIST2] )

# iterate over LIST1, matching list1 elements with corresponding list2
elements
pairs = [( L, lookup_table[L[0]]) for L in LIST1 if L[0] in
lookup_table]

# make whatever kind of modifications you want
for list_item, dictionary_item in pairs:
    dictionary_item['VERIFIED'] = list_item[2]  # or something




And- If you're using Python 2.4, you can get more efficient memory
usage out of this by using generator expressions instead of list
comprehensions.




More information about the Python-list mailing list