Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python reversing nested dictionaries

I want to take a nested dictionary and reverse the values for example

input = { "a" : { "x": 2, "y": 3 },
          "b" : { "x": 5, "z": 7 } }
output = {'y': {'a': 3},
          'x': {'a': 2, 'b': 5},
          'z': {'b': 7} }

what I have:

def reverse_nest_dicts(nested_dict):
    reverse_nest_dict = {}
    for k, v in nested_dict:
        for k2, v2 in nested_dict.values():
            reverse_nest_dict[k2][k] = v2
    return reverse_nest_dict
like image 627
user2014852 Avatar asked Oct 24 '25 18:10

user2014852


1 Answers

for k2, v2 in nested_dict.values():

should be

for k2, v2 in v.items():

(Also note that if you're using Python 2.x, it may be more efficient to use .iteritems() instead of .items().)


You also need to make sure the sub-dictionaries are initialized - you can do this by either using defaultdict...

from collections import defaultdict
reverse_nest_dict = defaultdict(dict)

...or by using setdefault:

reverse_nest_dict.setdefault(k2, {})[k] = v2
like image 77
Amber Avatar answered Oct 26 '25 07:10

Amber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!