简体   繁体   English

使用 python 反向嵌套字典

[英]reverse nested dicts using python

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.我正在尝试反转 python 字典。

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按照上面帖子的建议,我尝试了frozen set ,但仍然遇到同样的错误

I expect my output to be like as below我希望我的 output 如下所示

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

You can use nested dict comprehension:您可以使用嵌套的 dict 理解:

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'}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM