Abel Valdes
Abel Valdes

Reputation: 37

Python34: Using Dictionary Comprehension to Copy Values form one list of dictionaries to another

I am writing a script to process data so I have a list containing dictionaries with calculated values. Once I calculate new ones I want to append the appropriate dictionary with new entries.

I know I could do this with list or np array, but I want to learn how to use dictionaries. I also just started using list comprehension so I want to get a better understanding on how to use it appropriately. So making life hard on myself.

Here is simplified examples.

I calculate values and place them in the dictionary, which then goes in a list to correspond for each entry.

A=[{'low':1},{'low':2}]
print(A)
[{'low': 1}, {'low': 2}]   # entry 0 corresponds to sample 1 and the next to sample 2

B=[{'hi':1},{'hi':2}]
print(B)
[{'hi': 1}, {'hi': 2}]   # entry 0 corresponds to sample 1 and the next to sample 2

C=[{}]*len(A)   # initialize list to contain a dictionary for each sample. Each dictionary will receive the corresponding values copied from A and B
print(C)
[{}, {}]

Now I try to use dictionary comprehensions

{C[x].update(A[x]) for x in range(len(A))}
print(C)
[{'low': 2}, {'low': 2}]

The results is not what I expected. I want something like this:

[{'low':1,'high':1},{'low':1,'high':1}]

What am I not understanding here...

Thanks

Upvotes: 0

Views: 145

Answers (2)

Alfe
Alfe

Reputation: 59546

The term C=[{}]*len(A) creates a list of len(A) entries which all are the same dictionary. Changes to C[0] will also change C[1] because the two are identical.

Use C = [ {} for _ in A ] to create a new dictionary as each element of the list.

But all in all, as I mentioned in the comment above, I would consider appending the new dictionaries to an existing list; that sounds most like what you originally intended.

Upvotes: 1

chepner
chepner

Reputation: 532053

You need to use A and B together to update C. Here's one possible solution.

A=[{'low':1},{'low':2}]
B=[{'hi':1},{'hi':2}]

C = [dict(a.items() + b.items()) for a,b in zip(A, B)]

Upvotes: 1

Related Questions