Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap keys of nested dictionaries

I have a dictionary as follows:

Each key has a dictionary associated with it.

dict_sample = {'a': {'d0': '1', 'd1': '2', 'd2': '3'}, 'b': {'d0': '1'}, 'c': {'d1': '1'}}

I need the output as follows:

output_dict = {'d0': {'a': 1, 'b': 1}, 'd1': {'a': 2, 'c': 1}, 'd2': {'a': 3}}

I'd appreciate any help on the pythonic way to achieve this. Thank You !

like image 747
Vandhana Avatar asked Sep 06 '25 09:09

Vandhana


1 Answers

You can use dict.setdefault on a new dict with a nested loop:

d = {}
# for each key and sub-dict in the main dict
for k1, s in dict_sample.items():
    # for each key and value in the sub-dict
    for k2, v in s.items():
        # this is equivalent to d[k2][k1] = int(v), except that when k2 is not yet in d,
        # setdefault will initialize d[k2] with {} (a new dict)
        d.setdefault(k2, {})[k1] = int(v)

d would become:

{'d0': {'a': 1, 'b': 1}, 'd1': {'a': 2, 'c': 1}, 'd2': {'a': 3}}
like image 169
blhsing Avatar answered Sep 08 '25 12:09

blhsing