1

This is a great primer but doesn't answer what I need: Combining two sorted lists in Python

I have two Python lists, each is a list of datetime,value pairs:

list_a = [['1241000884000', 3], ['1241004212000', 4], ['1241006473000', 11]]

And:

list_x = [['1241000884000', 16], ['1241000992000', 16], ['1241001121000', 17], ['1241001545000', 19], ['1241004212000', 20], ['1241006473000', 22]]
  1. There are actually numerous list_a lists with different key/values.
  2. All list_a datetimes are in list_x.
  3. I want to make a list, list_c, corresponding to each list_a which has each datetime from list_x and value_a/value_x.

Bonus:

In my real program, list_a is actually a list within a dictionary like so. Taking the answer to the dictionary level would be:

dict = {object_a: [['1241000884000', 3], ['1241004212000', 4], ['1241006473000', 11]], object_b: [['1241004212000', 2]]}

I can figure that part out though.

Community
  • 1
  • 1
Adam Nelson
  • 7,932
  • 11
  • 44
  • 64
  • 2
    why don't you use dictionaries instead of lists? – SilentGhost Apr 29 '09 at 18:02
  • I could use a dictionary (or a set as recommended below). In the end though it needs to be a list because JSON will be looking for that. I'm fine with a dict answer. The answers below still aren't 100% even though I closed the question. – Adam Nelson Apr 29 '09 at 21:33

4 Answers4

4

Here's some code that does what you asked for. You can turn your list of pairs into a dictionary straightforwardly. Then keys that are shared can be found by intersecting the sets of keys. Finally, constructing the result dictionary is easy given the set of shared keys.

dict_a = dict(list_a)
dict_x = dict(list_x)

shared_keys = set(dict_a).intersection(set(dict_x))

result = dict((k, (dict_a[k], dict_x[k])) for k in shared_keys)
3

"I want to make a list, list_c, corresponding to each list_a which has each datetime from list_x and value_a/value_x."

def merge_lists( list_a, list_x ):
    dict_x= dict(list_x)
    for k,v in list_a:
        if k in dict_x:
            yield k, (v, dict_x[k])

Something like that may work also.

merged= list( merge_lists( someDict['object_a'], someDict['object_b'] )

This may be slightly quicker because it only makes one dictionary for lookups, and leaves the other list alone.

S.Lott
  • 384,516
  • 81
  • 508
  • 779
2

Nothing beats a nice functional one-liner:

reduce(lambda l1,l2: l1 + l2, list)
sth
  • 222,467
  • 53
  • 283
  • 367
misiu_mp
  • 909
  • 1
  • 12
  • 17
0

Could try extend:

list_a.extend(list_b)
sth
  • 222,467
  • 53
  • 283
  • 367
d-rave
  • 1