【发布时间】:2019-06-09 20:10:38
【问题描述】:
我有一个来自 json 响应的嵌套字典对象,我正在尝试使用该字典中的特定键:值对创建一个新字典。因为这一切都在一个类中,并且表达了函数 作为方法。
基本代码流程:
Function1:取d并检查d.keys()是否为'result'
函数2:如果F1为真:
clean_result = x
for x in self.cleanResult(d['result']):
clean_result = x
return clean_result
功能3:
def cleanResult(self, d):
for x in d:
yield {x['subject'],x['relationship'],x['object'],x['certainty']}
我无法理解如何创建这样的方法并返回复数字典。当我打印cleanResult() 生成器时,它会打印两个字典,但是当return clean_result 它只返回一个结果。谢谢。
我一直在创建不同类型的方法来处理字典数据、提取数据并创建多个字典并返回该值,但无法完成。
json文件的字典
d = {
"result": [
{
"objectMetadata": {
"en": [
{
"data": "A Romance Language, belonging to the Indo-European family that is an official Language in 29 countries, most of which form la francophonie (in French), the community of French-speaking countries.",
"dataType": "md"
}
]
},
"object": "French",
"subject": "s",
"factID": "WA:RF: 5877200994d54b1bc00004d29a1838f2dd31d9c1bc561da3d5a7871ad1b4c352",
"relationship": "speaks",
"relationshipType": "speaks",
"certainty": 100
},
{
"objectMetadata": {
"en": [
{
"data": "German is a West Germanic Language that is mainly spoken in Central Europe",
"dataType": "md"
}
]
},
"object": "German",
"subject": "s",
"factID": "WA:RF: 73493afc878bc9c09917dd1108950007259b04f5a2c36bf8066fe54fa111610b",
"relationship": "speaks",
"relationshipType": "speaks",
"certainty": 85
}
],
"stats": {
"getDBFact": {
"calls": 16,
"items": 8,
"ms": 28
},
"callDatasource": {
"calls": 0,
"ms": 0
},
"ensureCache": {
"ms": 5
},
"setDBFact": {
"calls": 4,
"ms": 34
},
"updateDBFact": {
"calls": 0,
"ms": 0
},
"totalMS": 117,
"approxEngineMS": 6,
"totalConditionCount": 8,
"invocationStartTime": 1560093937522
},
"createdAt": 1560093937582,
"sid": "853986e0-4e9e-4655-b63e-7491d4a62464"
}
我希望收到的预期结果是以下格式的字典列表:
clean_result =
{'1':{'subject':'s','relationship':'speaks':'object':'French','certainty':'100'},
'2':{'subject':'s','relationship':'speaks':'object':'Germany','certainty':'75'}}
【问题讨论】:
-
clean_result看起来不像列表,您希望它是词典词典还是词典列表? -
@arjithn 无论哪种方式。谢谢。
标签: json python-3.x dictionary