Merging dictionary value lists in python

As a one-liner, with a dictionary comprehension:

new = {key: value + two[key] + [three[key]] for key, value in one.iteritems()}

This creates new lists, concatenating the list from one with the corresponding list from two, putting the single value in three into a temporary list to make concatenating easier.

Or with a for loop updating one in-place:

for key, value in one.iteritems():
    value.extend(two[key])
    value.append(three[key])

This uses list.extend() to update original list in-place with the list from two, and list.append() to add the single value from three.

Where you went wrong:

  • your first attempt creates a new list with the values from one, two and three nested within rather than concatenating the existing lists. Your attempt to clean that up just copied those nested lists across.

  • Your second attempt didn’t work because the value in three is not a list so could not be concatenated. I created a new list just for that one value.

  • Your last attempt should not have used list.append() in a generator expression, because you store the return value of that method, which is always None (its change is stored in v directly and the list doesn’t need returning again).

Demo of the first approach:

>>> one={'a': [1, 2], 'c': [5, 6], 'b': [3, 4]}
>>> two={'a': [2.4, 3.4], 'c': [5.6, 7.6], 'b': [3.5, 4.5]}
>>> three={'a': 1.2, 'c': 3.4, 'b': 2.3}
>>> {key: value + two[key] + [three[key]] for key, value in one.iteritems()}
{'a': [1, 2, 2.4, 3.4, 1.2], 'c': [5, 6, 5.6, 7.6, 3.4], 'b': [3, 4, 3.5, 4.5, 2.3]}

Leave a Comment