0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

This updates the first list in-place. Note that the i = None assignment is entirely redundant here. @user3587412: I'm fine with this if this answer helped you most, but you cannot mark both answers as helpful. It is one or the other only. :-)
@MartijnPieters- you are correct , being java guy used to of initializing variables.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.