Merge a a tuple with the same key

  • A+
Category:Languages

How to merge a tuple with the same key

list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])] 

and turn them into

list_2 = [("AAA", [123, 456]), ("AAW", [147, 124])] 

 


The most performant approach is to use a collections.defaultdict dictionary to store data as an expanding list, then convert back to tuple/list if needed:

import collections  list_1 = [("AAA", [123]), ("AAA", [456]), ("AAW", [147]), ("AAW", [124])]  c = collections.defaultdict(list) for a,b in list_1:     c[a].extend(b)  # add to existing list or create a new one  list_2 = list(c.items()) 

result:

[('AAW', [147, 124]), ('AAA', [123, 456])] 

note that the converted data is probably better left as dictionary. Converting to list again loses the "key" feature of the dictionary.

On the other hand, if you want to retain the order of the "keys" of the original list of tuples, unless you're using python 3.6/3.7, you'd have to create a list with the original "keys" (ordered, unique), then rebuild the list from the dictionary. Or use an OrderedDict but then you cannot use defaultdict (or use a recipe)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: