Search code examples
pythondictionarymappingdefaultdict

Dictionary Formatting and defaultdict function


I have a dictionary which is the format of {(a,b):c, (a2,b2):c2 and so on}. From this format, there are more than one key of a2, a and so on and for each a, a2 the b, b2 however occurs only once and the value c,c2 for each item varies. What i need is to make a dictionary of dictionary values and single integer keys in this format: {a:{b:c,b2:c2}} assuming that before, a and a2 are the same value.

Cheers guys (use defaultdict if possible). in PYTHON.


Solution

  • if D is the input dict, then

    from collections import defaultdict
    res = defaultdict(dict)
    for (a,b),c in D.items():
        res[a][b] = c