【问题标题】:Collect specific items from dictionary values and create a new dictionary从字典值中收集特定项目并创建一个新字典
【发布时间】: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


【解决方案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}}

【讨论】:

    猜你喜欢
    • 2021-04-17
    • 1970-01-01
    • 2015-01-30
    • 2022-10-05
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多