user3587412
user3587412

Reputation: 1053

Adding JSON attributes using Python?

I'm trying to combine data using Python. For an example, I want to combine

[{'foo': 'something'}, {'foo': 'something else'}, {'foo': 'something else'}]

and

[{'bar': 'else'}, {'bar': 'else else'}, {'bar': 'else else'}]

to something like this:

[{'foo: 'something', 'bar': 'else'}, {'foo': 'something else', 'bar': 'else else'}, {'foo': 'something else', 'bar': 'else else'}]

Would this be possible in Python?

Upvotes: 0

Views: 136

Answers (2)

ni3ns
ni3ns

Reputation: 39

The result will be in a

a = [{'foo': 'something'}, {'foo': 'something else'}, {'foo': 'something else'}] 
b = [{'bar': 'else'}, {'bar': 'else else'}, {'bar': 'else else'}]
for i,j in zip(a,b):
     i.update(j)
print a

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122342

All you need to do is produce a new dictionary for each two input dictionaries. Use zip() to produce pairs:

result = [dict(a, **b) for a, b in zip(first, second)]

where first and second are your input lists. dict() creates a copy of an existing dictionary, but the **b syntax is a bit of a trick to add additional keys.

Upvotes: 1

Related Questions