【问题标题】:How do I get data from a nested dict?如何从嵌套字典中获取数据?
【发布时间】:2021-12-24 14:09:30
【问题描述】:

您好,我正在尝试从网站的 API 调用中获取特定数据。这是我收到的数据

这是我收到的数据

{'type': 'NonStockItem', 'attributes': [], 'id': '1', 'description': 'Ikke lagerførte varer høy sats'}
{'type': 'NonStockItem', 'attributes': [], 'id': '2', 'description': 'Ikke lagerførte varer middels sats'}
{'type': 'NonStockItem', 'attributes': [], 'id': '3', 'description': 'Ikke lagerførte varer lav sats'}
{'type': 'NonStockItem', 'attributes': [], 'id': '4', 'description': 'Ikke lagerførte varer avgiftsfri'}
{'type': 'FinishedGoodItem', 'attributes': [{'attributeId': 'NETTBUTIKK', 'description': 'WEB', 'required': False, 'attributeType': 'Text', 'details': []}], 'id': '5', 'description': 'Lagerførte varer høy sats'}
{'type': 'FinishedGoodItem', 'attributes': [], 'id': '6', 'description': 'Lagerførte varer middels sats'}
{'type': 'FinishedGoodItem', 'attributes': [], 'id': '7', 'description': 'Lagerførte varer avgiftsfri'}
{'type': 'LaborItem', 'attributes': [], 'id': '8', 'description': 'Tjenester (prosjekt)'}
{'type': 'ExpenseItem', 'attributes': [], 'id': '9', 'description': 'Utgifter (Reise)'}
{'type': 'FinishedGoodItem', 'attributes': [{'attributeId': 'NETTBUTIKK', 'description': 'WEB', 'required': True, 'attributeType': 'Text', 'details': []}], 'id': 'ONLINE', 'description': 'Online'}
{'type': 'FinishedGoodItem', 'attributes': [{'attributeId': 'NETTBUTIKK', 'description': 'WEB', 'required': False, 'attributeType': 'Text', 'details': []}, {'attributeId': 'WEB2', 'description': 'tilgjengelighet i nettbutikk', 'required': True, 'attributeType': 'Combo', 'details': [{'id': 'Ikke Inne', 'description': 'Produktet er utsolgt.'}, {'id': 'Inne', 'description': 'tilgjengelig i nettbutikk'}]}], 'id': 'WEB', 'description': 'Tilgjengelig på nettbutikk.'}

这是对象字段

[
          {
            "type": "NonStockItem",
            "attributes": [
              {
                "attributeId": "string",
                "description": "string",
                "sortOrder": 0,
                "required": true,
                "attributeType": "Text"
    }
]

这是我的代码

if response.status_code == 200:
itemClass = json.loads(response.text)

for item in itemClass:
      print(item["type"])
      print(item["description"])
      print(item["attributes"])

我要做的是只获取具有现有attributeId 的属性。我有点卡住了,因为属性数组中的数据是一个字典,我怎样才能得到键值?

当前输出:

    NonStockItem
Ikke lagerførte varer høy sats
[]
NonStockItem
Ikke lagerførte varer middels sats
[]
NonStockItem
Ikke lagerførte varer lav sats
[]
NonStockItem
Ikke lagerførte varer avgiftsfri
[]
FinishedGoodItem
Lagerførte varer høy sats
[{'attributeId': 'NETTBUTIKK', 'description': 'WEB', 'required': False, 'attributeType': 'Text', 'details': []}]
FinishedGoodItem
Lagerførte varer middels sats
[]
FinishedGoodItem
Lagerførte varer avgiftsfri
[]
LaborItem
Tjenester (prosjekt)
[]
ExpenseItem
Utgifter (Reise)
[]
FinishedGoodItem
Online
[{'attributeId': 'NETTBUTIKK', 'description': 'WEB', 'required': True, 'attributeType': 'Text', 'details': []}]
FinishedGoodItem
Tilgjengelig på nettbutikk.
[{'attributeId': 'NETTBUTIKK', 'description': 'WEB', 'required': False, 'attributeType': 'Text', 'details': []}, {'attributeId': 'WEB2', 'description': 'tilgjengelighet i nettbutikk', 'required': True, 'attributeType': 'Combo', 'details': [{'id': 'Ikke Inne', 'description': 'Produktet er utsolgt.'}, {'id': 'Inne', 'description': 'tilgjengelig i nettbutikk'}]}]

我只想要包含 attributeId 的类型

【问题讨论】:

  • 能否提供更详细的数据样本。
  • @Thekingis007 我现在更新了问题,预期的输出只有包含 attributeId 的项目,我不想要空数组
  • 我的意思是你的输入不是输出,但我希望我的解决方案能回答你的问题。

标签: python loops dictionary


【解决方案1】:

我假设您正在处理的列表可以使用 lst[0]['attributes'] 访问。

尝试以下使用列表理解的方法:

lst = [
        {
            "type": "NonStockItem",
            "attributes": [
                {
                    "attributeId": "string",
                    "description": "string",
                    "sortOrder": 0,
                    "required": True,
                    "attributeType": "Text"
                    },
                {
                    # Note that it does not have attributeId
                    "description": "string",
                    "sortOrder": 0,
                    "required": True,
                    "attributeType": "Text"
                    }
                ]
            }
        ]

attrs = lst[0]['attributes']
output = [d for d in attrs if 'attributeId' in d]
print(output)

输出:

[{'attributeId': 'string', 'description': 'string', 'sortOrder': 0, 'required': True, 'attributeType': 'Text'}]

注意输出只有一个元素;在我给出的输入示例中,第二个字典没有attributeId

【讨论】:

    【解决方案2】:

    考虑到您的数据样本和输出,我认为的最佳解决方案是验证 item["attributes"] 内部是否有值:

    代码:

    itemclass = [{'type': 'NonStockItem', 'attributes': [], 'id': '1', 'description': 'Ikke lagerførte varer høy sats'},
    {'type': 'NonStockItem', 'attributes': [], 'id': '2', 'description': 'Ikke lagerførte varer middels sats'},
    {'type': 'NonStockItem', 'attributes': [], 'id': '3', 'description': 'Ikke lagerførte varer lav sats'},
    {'type': 'NonStockItem', 'attributes': [], 'id': '4', 'description': 'Ikke lagerførte varer avgiftsfri'},
    {'type': 'FinishedGoodItem', 'attributes': [{'attributeId': 'NETTBUTIKK', 'description': 'WEB', 'required': False, 'attributeType': 'Text', 'details': []}], 'id': '5', 'description': 'Lagerførte varer høy sats'},
    {'type': 'FinishedGoodItem', 'attributes': [], 'id': '6', 'description': 'Lagerførte varer middels sats'},
    {'type': 'FinishedGoodItem', 'attributes': [], 'id': '7', 'description': 'Lagerførte varer avgiftsfri'},
    {'type': 'LaborItem', 'attributes': [], 'id': '8', 'description': 'Tjenester (prosjekt)'},
    {'type': 'ExpenseItem', 'attributes': [], 'id': '9', 'description': 'Utgifter (Reise)'},
    {'type': 'FinishedGoodItem', 'attributes': [{'attributeId': 'NETTBUTIKK', 'description': 'WEB', 'required': True, 'attributeType': 'Text', 'details': []}], 'id': 'ONLINE', 'description': 'Online'},
    {'type': 'FinishedGoodItem', 'attributes': [{'attributeId': 'NETTBUTIKK', 'description': 'WEB', 'required': False, 'attributeType': 'Text', 'details': []}, {'attributeId': 'WEB2', 'description': 'tilgjengelighet i nettbutikk', 'required': True, 'attributeType': 'Combo', 'details': [{'id': 'Ikke Inne', 'description': 'Produktet er utsolgt.'}, {'id': 'Inne', 'description': 'tilgjengelig i nettbutikk'}]}], 'id': 'WEB', 'description': 'Tilgjengelig på nettbutikk.'}]
    
    for item in itemclass:
        if item["attributes"]:
            print(item["type"])
            print(item["description"])
            print(item["attributes"])
    

    输出:

    FinishedGoodItem
    Lagerførte varer høy sats
    [{'attributeId': 'NETTBUTIKK', 'description': 'WEB', 'required': False, 'attributeType': 'Text', 'details': []}]
    FinishedGoodItem
    Online
    [{'attributeId': 'NETTBUTIKK', 'description': 'WEB', 'required': True, 'attributeType': 'Text', 'details': []}]
    FinishedGoodItem
    Tilgjengelig på nettbutikk.
    [{'attributeId': 'NETTBUTIKK', 'description': 'WEB', 'required': False, 'attributeType': 'Text', 'details': []}, {'attributeId': 'WEB2', 'description': 'tilgjengelighet i nettbutikk', 'required': True, 'attributeType': 'Combo', 'details': [{'id': 'Ikke Inne', 'description': 'Produktet er utsolgt.'}, {'id': 'Inne', 'description': 'tilgjengelig i nettbutikk'}]}]
    

    【讨论】:

    • 有没有办法访问属性内的字段并对其进行过滤/排序?
    • @SuzdarIbrahim 我已经编辑了我的解决方案,请查看。
    • 我试过了,我收到了这个错误消息:IndexError: list index out of range
    • @SuzdarIbrahim 这就是为什么我要求提供示例输入数据,您能否在问题中提供它?
    • 我已经更新了
    【解决方案3】:

    Pandas json_normalize 也可以用于此:

    import json
    import pandas as pd
    
    response = '''[
        {
            "type": "NonStockItem",
            "attributes": [
            {
                "attributeId": "string1",
                "description": "string",
                "sortOrder": 0,
                "required": true,
                "attributeType": "Text"
            },
             {
                "attributeId": "string2",
                "description": "string",
                "sortOrder": 0,
                "required": true,
                "attributeType": "Text"
            }]
        },
        {
            "type": "NonStockItem",
            "attributes":[]
        },
        {
            "type": "NonStockItem",
            "attributes": [
            {
                "attributeId": "string3",
                "description": "string",
                "sortOrder": 0,
                "required": true,
                "attributeType": "Text"
            },
             {
                "attributeId": "string4",
                "description": "string",
                "sortOrder": 0,
                "required": true,
                "attributeType": "Text"
            }]
        }    
        ]
    '''
    itemClass = json.loads(response)
    
    
    print(pd.concat([pd.json_normalize(x["attributes"]) for x in itemClass], 
        ignore_index=True))
    
      attributeId description  sortOrder  required attributeType
    0     string1      string          0      True          Text
    1     string2      string          0      True          Text
    2     string3      string          0      True          Text
    3     string4      string          0      True          Text
    

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      • 2015-03-23
      • 2018-04-20
      相关资源
      最近更新 更多