python - Given 3 dicts of varying size, how would I find the intersections and values? -


i looked intersections of dictionaries, , tried use set library, couldn't figure out how show values , not pull out keys work them, i'm hoping help. i've got 3 dictionaries of random length:

dict_a= {1: 488, 2: 336, 3: 315, 4: 291, 5: 275}  dict_b={2: 0, 3: 33, 1: 61, 5: 90, 15: 58}  dict_c= {1: 1.15, 9: 0, 2: 0.11, 15: 0.86, 19: 0.008, 20: 1834} 

i need figure out keys in dictionary a, b, , c, , combine new dictionary. need figure out keys in dictionary a&b or a&c or b&c, , pull out new dictionary. should have left on in a, b, , c ones unique dictionary.

so, eventually, i'd wind separate dictionaries, follows:

total_intersect= {1: {488, 61, 1.15}, 2: {336, 0, 0.11}} a&b_only_intersect = {3: {315,33}, 5:{275,90}} (then dicts a&c intersect , b&c intersect) dict_a_leftover= {4:291} (and dicts leftovers b , c) 

i thought using zip, it's important values stay in respective places, meaning can't have values in c position. awesome!

   lst =  [dict_a,dict_b,dict_c]     total_intersect_key = set(dict_a) & set(dict_b) & set(dict_c)    total_intersect = { k:[ item[k] item in lst ]  k in total_intersect_key} 

output:

{1: [488, 61, 1.15], 2: [336, 0, 0.11]} 

for other question reduce lst elements

lst = [dict_a,dict_b] a&b_only_intersect = { k:[ item[k] item in lst ]  k in set(dict_a.keys) & set(dict_b)} 

also can convert function

def intersect(lst):      return { k:[ item[k] item in lst if k in item ]  k in reduce( lambda x,y:set(x)&set(y), lst ) } 

example:

>>> {1: 488, 2: 336, 3: 315, 4: 291, 5: 275} >>> b {1: 61, 2: 0, 3: 33, 5: 90, 15: 58} >>> c {1: 1.15, 2: 0.11, 9: 0, 15: 0.86, 19: 0.008, 20: 1834} >>> intersect( [a,b] ) {1: [488, 61], 2: [336, 0], 3: [315, 33], 5: [275, 90]} >>> intersect( [a,c] ) {1: [488, 1.15], 2: [336, 0.11]} >>> intersect( [b,c] ) {1: [61, 1.15], 2: [0, 0.11], 15: [58, 0.86]} >>> intersect( [a,b,c] ) {1: [488, 61, 1.15], 2: [336, 0, 0.11]} 

-----update-----

def func( lst, intersection):      if intersection:          return { k:[ item[k] item in lst if k in item ]  k in reduce( lambda x,y:set(x)&set(y), lst ) }      else:          return { k:[ item[k] item in lst if k in item ]  k in reduce(lambda x,y:set(x).difference(set(y)), lst ) }  >>> func([a,c],false) {3: [315], 4: [291], 5: [275]} >>> func([a,b],false) {4: [291]} >>> func( [func([a,b],false),func([a,c],false)],true) {4: [[291], [291]]} 

one issue: need take duplication out final result or try improve func itself.

{k:set( reduce( lambda x,y:x+y, v) ) k,v in func( [func([a,b],false),func([a,c],false)],true).iteritems()}  {4: set([291])} 

Comments

Popular posts from this blog

jOOQ update returning clause with Oracle -

java - Warning equals/hashCode on @Data annotation lombok with inheritance -

java - BasicPathUsageException: Cannot join to attribute of basic type -