开发者

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


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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜