Harry
Harry

Reputation: 13329

How to combine two lists of dictionaries

How would I combine these two with python ?

d1 = [{a:1, b:2},{a:2,b:5}]
d2 = [{s:3, f:1},{s:4, f:9}]

I would just like to add d2 to the end if d1, so:

d2 = [{a:1, b:2},{a:2,b:5},{s:3, f:1},{s:4, f:9}]

Upvotes: 2

Views: 7211

Answers (3)

Yauhen Yakimovich
Yauhen Yakimovich

Reputation: 14231

The correct answer to your question is dict.extend() (as pointed by Ant). However your example concerns list concatenation, not dictionary extension.

So, if both arguments are lists you can concatenate them as in:

> d1 + d2
[{'a': 1, 'b': 2}, {'a': 2, 'b': 5}, {'s': 3, 'f': 1}, {'s': 4, 'f': 9}]

which is equivalent to calling list.extend():

L.extend(iterable) -- extend list by appending elements from the iterable

Upvotes: 7

Ashley Davis
Ashley Davis

Reputation: 10039

This is how I do it in Python 2.7:

combined = {}
combined.update(d1)
combined.update(d2)

It is good to define a utility function to do this:

def merge(d1, d2):
    ''' Merge two dictionaries. '''
    merged = {}
    merged.update(d1)
    merged.update(d2)
    return merged

Upvotes: 4

Ant
Ant

Reputation: 5424

d1.extend(d2) however you're combining two lists not two dictionaries

Upvotes: 6

Related Questions