-2

I already referred these posts here, here and here.

I have a sample dict like as shown below

t = {'thisdict':{
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
},
'thatdict':{
  "af": "jfsak",
  "asjf": "jhas"}}

I am trying to reverse a python dictionary.

My code looks like below

print(type(t))
inv = {v:k  for k,v in t.items()} # option 1 - error here
print(inv) 
frozenset(t.items())  # option 2 - error here

Instead I get the below error

TypeError: unhashable type: 'dict'

Following the suggestion from post above, I tried frozen set, but still I get the same error

I expect my output to be like as below

t = {'thisdict':{
  "Ford":"brand",
  "Mustang":"model",
  1964:"year"
},
'thatdict':{
  "jfsak":"af",
  "jhas":"asjf"}}
desertnaut
  • 57,590
  • 26
  • 140
  • 166
The Great
  • 7,215
  • 7
  • 40
  • 128

1 Answers1

2

You can use nested dict comprehension:

t = {'thisdict': {"brand": "Ford", "model": "Mustang", "year": 1964},
     'thatdict': {"af": "jfsak", "asjf": "jhas"}}

output = {k_out: {v: k for k, v in d.items()} for k_out, d in t.items()}
print(output)
# {'thisdict': {'Ford': 'brand', 'Mustang': 'model', 1964: 'year'}, 'thatdict': {'jfsak': 'af', 'jhas': 'asjf'}}
j1-lee
  • 13,764
  • 3
  • 14
  • 26