python 2.7 - Comparing two dictionary keys and values -
i have 2 dictionaries in i'm trying first find matching key d1 in d2, output subtraction of 3rd value in key both dictionaries..can done in 1 loop function? first tried doing in 2 steps gives me empty list d3, tried use loop gives me error v not defined.
d1 = {'alpha': [5, 9, 11], 'beta': [6, 10, 20], 'gamma': [12, 15, 19]} d2 = {'alpha': [3, 8, 20], 'omega': [15, 32, 40], 'ro': [22, 25, 4]} d3 = {} key in d1: if key in d2: d3.setdefault(key, []).append print d3 #should d3 = {'alpha': [3, 8, 20]} #compare , calculate difference between 20 , 11 in alpha key value = d3(key, v(2)) - d1(key, v(2)) print value #value = 9 #can loop find key in d2 , matches key in d1 #and calculate difference? key in d1: if key in d2: value = d2(key, v(2)) - d1(key, v(2)) print value
thoughts?
thank you. -jon
you use dictionary comprehension:
diff = {key: d2[key][2] - d1[key][2] key in d2 if key in d1} # {'alpha': 9}
this give dictionary in keys common d2
, d1
, values difference of third values in lists of d1
, d2
Comments
Post a Comment