【问题标题】:JSON, Python, Search for value in dict based on another value in same dict listJSON,Python,根据同一字典列表中的另一个值在字典中搜索值
【发布时间】:2021-11-10 11:21:17
【问题描述】:

我有一个 JSON 字典列表,我想根据同一个字典中的另一个值从中提取一个值。我尝试了多种获取价值的方法,但我找不到任何有效的方法。字典列表可以有可变数量的字典,因此在使用编号括号时它并不总是给出正确的答案。 (['objectEntries'][0]['attributes'][5]["subValue"][0]['displayValue'])

objectEntries dict 列表包含更多的 dicts,但我将其删除了大小。我将遍历所有的 dicts 以提取相同的值。

我有一个 json:

{
    "objectEntries": [
        {
            "label": "test",
            "attributes": [
                {
                    "id": 0,
                },
                {
                    "id": 1,
                },
                {
                    "id": 2,
                },
                {
                    "id": 3,
                },
                {
                    "id": 4,
                },
                {
                    "Id": 5,
                    "subValue": [
                        {
                            "displayValue": "This",
                        }
                    ],
                    "objectId": 26085
                },
            ],
            "name": "test"
        }
        {
            ...
        }
    ]
}

我想从 subValue.displayValue 中提取值“This”,其中 objectEntries.attributes.id = 5。 我对 JSON 还很陌生,所以如果能帮助我朝着正确的方向发展,我们将不胜感激。

到目前为止我所做的:

import json
import pandas as pd


with open('fulldump.json', 'r') as f:
    data = json.load(f)

for object in data['objectEntries']:
    name = object['name']
    get = object['attributes'][5]['subValue'][0]['displayValue']

    table.append([name, get])

df = pd.DataFrame(table, columns=['Name', 'Get'])

变量“get”的值通常是正确的,但对于某些objectEntries,属性中缺少一个或多个dict,这会导致get读取错误的值。

【问题讨论】:

  • 你尝试过做什么?你能发布一个最小的可重现的例子吗?
  • 我已经用我目前所做的编辑了这篇文章。我几乎不知道从这里去哪里。

标签: python json dictionary


【解决方案1】:

也许您可以只检查键而不是猜测要操作的正确字典?

例如

import json
import pandas as pd


with open('fulldump.json', 'r') as f:
    data = json.load(f)

for object in data['objectEntries']:
    name = object['name']
    relevant_dict = filter(lambda x: 'subValue' in x, object['attributes'])[0]
    get = relevant_dict['subValue'][0]['displayValue']

    table.append([name, get])

df = pd.DataFrame(table, columns=['Name', 'Get'])

此答案假定只有一个属性条目将包含所需的键

编辑:

如果你想每次都专门获取id为5的item,你可以修改filter如下:

import json
import pandas as pd


with open('fulldump.json', 'r') as f:
    data = json.load(f)

for object in data['objectEntries']:
    name = object['name']
    relevant_dict = filter(lambda x: x['Id'] == 5, object['attributes'])[0]
    get = relevant_dict['subValue'][0]['displayValue']

    table.append([name, get])

df = pd.DataFrame(table, columns=['Name', 'Get'])

【讨论】:

  • 请注意,如果您知道要检查的 dict 中的 id 始终为 5,例如 id 3 将丢失,您可以检查此值而不是subValue
  • 是的,id 将始终为 5,无论是否缺少 id: 3 的dict。这就是我想要完成的。我正在使用 python3,所以我必须在 filter() 函数之前插入一个 list() 函数以避免错误:TypeError: 'filter' object is not subscriptable。但是,我很难用“where id = 5”的表达式替换“subValue”键。尝试了一些变体,包括 '5'、5、'id' = 5 等。
  • 我编辑了答案以添加潜在客户(未经测试)。如果要确保比较的是同一类型,可以改用str(x['Id']) == '5'
  • 您可能会遇到错误,因为其他项目没有密钥Id(它们有id,带有小写的i)
  • 是的,这正是我想要的!非常感谢你的帮助!我最终创建了一个函数,因此我也可以查找其他值。 ``` def find_keyvaluepair(value): try: intermediate = list(filter(lambda x: x['id'] == value, object['attributes']))[0] ans = intermediate['subValue'][ 0]['displayValue'] 除了 IndexError: ans = '' return ans ```
猜你喜欢
  • 2017-07-29
  • 2021-05-31
  • 1970-01-01
  • 2017-11-06
  • 2016-04-23
  • 1970-01-01
  • 2021-07-13
  • 2016-07-15
  • 1970-01-01
相关资源
最近更新 更多