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"}}
CodePudding user response:
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'}}
