python - How to combine two dictionaries? One dict as key, another dict as value -


i have 2 dictionaries

dict0 = {'a':0, 'b':1, 'c':2}  dict1 = {0 : {'a0' : 0,'a1' : 1,'a2' : 2},          1 : {'b0' : 0,'b1' : 1,'b2' : 2},          2 : {'c0' : 0,'c1' : 1,'c2' : 2}} 

i combine dictionary combdict, uses keys of dict0 values combdict, , uses values of dict1 keys combdict

combdict = {{'a0':0,'a1':1,'a2':2}:'a',{'b0':0,'b1':1,'b2':2}'b',{'c0':0,'c1':1,'c2':2}:'c'} 

i know it's basic. logical code written, wrong.

combdict = {} k0, v0 in dict0:     combdict.values()= k0     k1,v1  in dict1:         combdict.keys() = v1 

any suggestion? thanks. btw if want make dictionaries more sense you, edit them.

because dictionaries mutable, cannot use dictionaries keys of dictionary or store them in set.

you'll have capture immutable 'snapshot' of dictionary instead:

def dict_to_key(d):     return tuple(sorted(d.items())) 

provided dictionary values not mutable either, can use return value of dict_to_key() function keys instead.

now can build combined dictionary:

combineddict = {dict_to_key(dict1[v]): k k, v in dict0.items()} 

demo:

>>> dict0 = {'a':0, 'b':1, 'c':2} >>> dict1 = {0 : {'a0' : 0,'a1' : 1,'a2' : 2}, ...          1 : {'b0' : 0,'b1' : 1,'b2' : 2}, ...          2 : {'c0' : 0,'c1' : 1,'c2' : 2}} >>> def dict_to_key(d): ...     return tuple(sorted(d.items())) ...  >>> {dict_to_key(dict1[v]): k k, v in dict0.items()} {(('b0', 0), ('b1', 1), ('b2', 2)): 'b', (('a0', 0), ('a1', 1), ('a2', 2)): 'a', (('c0', 0), ('c1', 1), ('c2', 2)): 'c'} 

Comments