3

I have a dictionary:

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

I want to switch the a and b keys of the dictionary. In other words, I want the resulting dictionary to be:

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

without using loops.

Here is what I have now using loops:

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 made into one line?

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
Antony Joseph
  • 255
  • 2
  • 7

1 Answers1

1

I assume that by without for loops you mean with comprehensions. Here is one possibility:

Code:

This could be compressed to one line, but I think two lines is a bit clearer, and likely not much less performant.

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}}
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135