2

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}]
0

3 Answers 3

7

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
0
6

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

4

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
1
  • >>> d1 = [{'a':1,'b':2},{'a':2,'b':5}] >>> d2 = [{'s':3,'f':1},{'s':2,'f':9}] >>> l3 = {} >>> l3.update(l1) >>> l3 {'a': 'b'} >>> l3.update(l2) >>> l3 {'a': 'b'} Sep 1, 2017 at 6:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.