从字典值中收集特定项并创建一个新字典

时间:2019-06-09 20:10:38

标签: json python-3.x dictionary

我有一个来自json响应的嵌套字典对象,我试图用该字典中的特定key:value对创建一个新字典。因为这一切都在一个类中,并且函数表达了出来 作为方法。

基本代码流:

功能1:取d并检查d.keys()是否为'result'

功能2:如果F1为true:

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

1 个答案:

答案 0 :(得分:1)

在此处找到的函数中,每次迭代都将覆盖clean_result的值。这是一个非常简单的修复,因为您可以更改代码:

clean_result = x
for x in self.cleanResult(d['result']):
   clean_result = x

return clean_result

if d.get('result'):  # returns True if found else None
   clean_result = {}
   for i, x in enumerate(self.cleanResult(d['result'])):  # loop returns index (i) and value (x)
      clean_result[str(i)] = x

   return clean_result

但这仍然只返回一组数据,而不是像预期数据那样的字典。

要返回字典,请使用以下代码:

def cleanResult(self, d):
  for x in d:
    yield {"subject": x["subject"], "relationship": x["relationship"], "object": x["object"], "certainty": x["certainty"]}

这将返回:

{'0': {'subject': 's', 'relationship': 'speaks', 'object': 'French', 'certainty': 100},
 '1': {'subject': 's', 'relationship': 'speaks', 'object': 'German', 'certainty': 85}}