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


i writing script process data have list containing dictionaries calculated values. once calculate new ones want append appropriate dictionary new entries.

i know list or np array, want learn how use dictionaries. started using list comprehension want better understanding on how use appropriately. making life hard on myself.

here simplified examples.

i calculate values , place them in dictionary, goes in list correspond each entry.

a=[{'low':1},{'low':2}] print(a) [{'low': 1}, {'low': 2}]   # entry 0 corresponds sample 1 , next sample 2  b=[{'hi':1},{'hi':2}] print(b) [{'hi': 1}, {'hi': 2}]   # entry 0 corresponds sample 1 , next sample 2  c=[{}]*len(a)   # initialize list contain dictionary each sample. each dictionary receive corresponding values copied , b print(c) [{}, {}] 

now try use dictionary comprehensions

{c[x].update(a[x]) x in range(len(a))} print(c) [{'low': 2}, {'low': 2}] 

the results not expected. want this:

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

what not understanding here...

thanks

the term c=[{}]*len(a) creates list of len(a) entries same dictionary. changes c[0] change c[1] because 2 identical.

use c = [ {} _ in ] create new dictionary each element of list.

but in all, mentioned in comment above, consider appending new dictionaries existing list; sounds intended.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -