Python: including keyword structure of a dictionary

I have a dictionary:

d = {'a1':{'b1':1, 'b2':2}, 'a2':{'b1':3, 'b2':4}}`.

      

I want to switch keys a

and b

dictionary. In other words, I want the resulting dictionary to be:

dd = {'b1':{'a1':1, 'a2':3}, 'b2':{'a1':2, 'a2':4}}

      

without using hinges.

This is what I now use in a loop:

d = {'a1':{'b1':1, 'b2':2}, 'a2':{'b1':3, 'b2':4}}
from collections import defaultdict
dd=defaultdict(dict)

for k in d.keys():
   for tmp_k in d.get(k).keys():
      dd[tmp_k][k] =d[k][tmp_k]
print dict(dd)

      

Can this be done in one line?

+3


source to share


1 answer


I assume that by without for loops

you mean with understanding. Here's one of the possibilities:

Code:

It could be condensed into one line, but I think the two lines are a little clearer and probably not much less efficient.



import itertools as it

d = {'a1': {'b1': 1, 'b2': 2}, 'a2': {'b1': 3, 'b2': 4}}

new_keys = set(it.chain.from_iterable(i.keys() for i in d.values()))
new_dict = {k: {i: v[k] for i, v in d.items()} for k in new_keys}

print(new_dict)

      

Results:

{'b1': {'a1': 1, 'a2': 3}, 'b2': {'a1': 2, 'a2': 4}}

      

+1


source







All Articles