简体   繁体   中英

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

I have two 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 would like to get a combine dictionary CombDict , which uses keys of Dict0 as the values for CombDict , and uses values of Dict1 as the keys for 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 very basic. My logical code is written, but definitely is wrong.

CombDict = {}
for k0, v0 in Dict0:
    CombDict.values()= k0
    for k1,v1  in Dict1:
        CombDict.keys() = v1

Any suggestion? Thanks. Btw if you want to make the dictionaries more sense to you, just edit them.

Because dictionaries are mutable, you cannot use dictionaries as keys of another dictionary or store them in a set.

You'll have to capture an immutable 'snapshot' of the dictionary instead:

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

Provided the dictionary values are not mutable either, you can use the return value of the dict_to_key() function as keys instead.

Now you can build the combined dictionary:

CombinedDict = {dict_to_key(Dict1[v]): k for 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 for 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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM