首页 > 解决方案 > JSON 文件格式的字典

问题描述

我有一个列表字典,我想以特定格式存储在 JSON 文件中。

格式:

{ "type" : 
     {"name" : "Predicted", "inward" : "is predicted by", "outward" : "predicts"},
                 "inwardIssue" : { "key" : issues_key[1]},
                 "outwardIssue":{"key":data2}
    }

字典中的数据:

{'CLOV-1984': ['CLOV-1979'], 'CLOV-1979': ['CLOV-1984'], 'CLOV-1970': ['CLOV-1951'], 'CLOV-1951': ['CLOV-1970'], 'CLOV-1910': ['CLOV-1909'], 'CLOV-1909': ['CLOV-1910'], 'CLOV-1853': ['CLOV-1849', 'CLOV-1845', 'CLOV-1842'], 'CLOV-1849': ['CLOV-1853', 'CLOV-1840'], 'CLOV-1845': ['CLOV-1853', 'CLOV-1840'], 'CLOV-1842': ['CLOV-1853', 'CLOV-1840'], 'CLOV-1840': ['CLOV-1849', 'CLOV-1845', 'CLOV-1842']}

我不断收到的错误是:

TypeError                                 Traceback (most recent call last)
<ipython-input-62-76678d843e45> in <module>
      8      {"name" : "Predicted", "inward" : "is predicted by", "outward" : "predicts"},
      9                  "inwardIssue" : { "key" : issues_key[1]},
---> 10                  "outwardIssue":{"key":data2}
     11     }
     12 })

TypeError: unhashable type: 'dict'

我是 Python 新手,正在尝试不同的东西。

import json


data = {}
data2 = []
data2 = dictIssues[issues_key[1]]
print(data2)
data['CLOV-1985'] = []
data['CLOV-1985'].append({
     { "type" : 
      {"name" : "Predicted", "inward" : "is predicted by", "outward" : 
          "predicts"},
                 "inwardIssue" : { "key" : issues_key[1]},
                 "outwardIssue":{"key":data2}
     }

})


with open('data.txt', 'w') as outfile:
    json.dump(data, outfile)

我应该创建一个循环,遍历字典中的所有键并获取列表并将其放入 JSON 文件的格式中。

标签: pythonjson

解决方案


推荐阅读