L-R
L-R

Reputation: 1232

zip 2 lists of dictionaries into 1

I have a first list like so

[{"name":"jon", "age":10}, {"name":"mary", "age":12}]

And a second list like so

[{"city":"nyc"}, {"city":"la"}]

And would like to combine them into a single list of dicts. They are assumed to be of same length too.

[{"name":"jon", "age":10, "city":"nyc"}, {"name":"mary", "age":12, "city":"la"}]

thanks!

Upvotes: 1

Views: 175

Answers (3)

Veedrac
Veedrac

Reputation: 60147

Three new ways, all direct variants:

from collections import ChainMap

first  = [{"name":"jon", "age":10}, {"name":"mary", "age":12}]
second = [{"city":"nyc"}, {"city":"la"}]

Firstly:

map(ChainMap, first, second)
#>>> <map object at 0x7fee1c53ddd0>

Note that this doesn't copy the objects. If you need it in an actual list:

[ChainMap(f, s) for f, s, in zip(first, second)]
#>>> [ChainMap({'name': 'jon', 'age': 10}, {'city': 'nyc'}), ChainMap({'name': 'mary', 'age': 12}, {'city': 'la'})]

If you need it copied:

[dict(ChainMap(f, s)) for f, s, in zip(first, second)]
#>>> [{'name': 'jon', 'age': 10, 'city': 'nyc'}, {'name': 'mary', 'age': 12, 'city': 'la'}]

Honestly this seems nicer to me than dict(first.items() + second.items()) and it's also quite stable.

Upvotes: 2

marxin
marxin

Reputation: 3922

Also simply:

for i in xrange(len(x)):
    x[i].update(y[i])

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

Using list comprehension:

>>> lis1 = [{"name":"jon", "age":10}, {"name":"mary", "age":12}]
>>> lis2 = [{"city":"nyc"}, {"city":"la"}]
>>> [dict(x, **y) for x, y in zip(lis1, lis2)]
[{'city': 'nyc', 'age': 10, 'name': 'jon'}, {'city': 'la', 'age': 12, 'name': 'mary'}]

As Guido dislikes dict(x, **y), another option is:

>>> [dict(x.items() + y.items()) for x, y in zip(lis1, lis2)]
[{'city': 'nyc', 'age': 10, 'name': 'jon'}, {'city': 'la', 'age': 12, 'name': 'mary'}]

Upvotes: 7

Related Questions