python function to swap dict's keys

Viewed 34

I have a nested dictionary.

x = {
'Jack': {'Age': '34', 'Location' : 'Chicago'}, 'Mary': {'Insurance': 'fullPaid', 'Age' : '27', 'Location' : 'London'}
}

What im trying to do is swap dict's keys so output dictionary would look like this:

{
'Age':{'Jack' : '34', 'Mary' : '27'}, 'Location': {'Jack' : 'Chicago', 'Mary' : 'London'}, 'Insurance': {'Mary' : 'fullPaid'} 
}

So far i got to this point:

y = defaultdict(list)
for key, values in x.items(): 
    for value in values:
        y[value].append(key)

where output is

defaultdict(<class 'list'>, {'Age': ['Jack', 'Mary'], 'Location': ['Jack', 'Mary'], 'Insurance': ['Mary']})
1 Answers

Close, but you need to use defaultdict(dict) & unpack the nested dict as well.

from collections import defaultdict

x = {
'Jack': {'Age': '34', 'Location' : 'Chicago'}, 'Mary': {'Insurance': 'fullPaid', 'Age' : '27', 'Location' : 'London'}
}

y = defaultdict(dict)
for name, attrs in x.items():
    for key, value in attrs.items():
        y[key][name] = value

print(dict(y))

result:

{'Age': {'Jack': '34', 'Mary': '27'}, 'Location': {'Jack': 'Chicago', 'Mary': 'London'}, 'Insurance': {'Mary': 'fullPaid'}}
Related