【问题标题】:scrape values from nested json dicts从嵌套的 json 字典中抓取值
【发布时间】:2019-11-13 17:38:23
【问题描述】:

我有如下示例所示的数据。它有 dict,它的键是列表。这些列表还包含字典。我想创建一个类似于下面所需输出的列表,其中我已经从数据中抓取了“Id”值。我一直在编写 for 循环来提取值,然后按键和值进行过滤。我在想也许有一种更简单的方法,比如使用正则表达式模式匹配来获取所有具有模式“u'Id':u'integer'”的东西。有没有人看到更简单的方法,或者可以建议代码从下面的嵌套字典中抓取“Id”值?

数据:

{u'distinct': [{u'__class__': u'tuple',
   u'__value__': [{u'Id': u'9624',
     u'classification': u'i',

     u'storeid': u'86'},

    {u'Id': u'41822',
     u'classification': u's/i',

     u'storeid': u'86'}]}],
 u'match': [{u'__class__': u'tuple',
   u'__value__': [{u'Id': u'38916',
     u'classification': u'c',

     u'storeid': u'125'},
    {u'Id': u'49462',
     u'classification': u'n/a',

     u'storeid': u'124'}]},
      {u'Id': u'46525',
     u'classification': u'h',
          u'storeid': u'158'}]}]}

想要的输出:

[9624,41822,49462,46525]

【问题讨论】:

    标签: json regex python-3.x dictionary


    【解决方案1】:

    我认为字典中有两个额外的 ]},你已经发布了,如果这是真的,那么你可以循环查看你想要的 ID 在哪里:

    d = {u'distinct': [{u'__class__': u'tuple', u'__value__': [{u'Id': u'9624', u'classification': u'i', u'storeid': u'86'}, {u'Id': u'41822', u'classification': u's/i', u'storeid': u'86'}]}], u'match': [{u'__class__': u'tuple',
                                                                                                                                                                                                             u'__value__': [{u'Id': u'38916', u'classification': u'c', u'storeid': u'125'}, {u'Id': u'49462', u'classification': u'n/a', u'storeid': u'124'}]}, {u'Id': u'46525', u'classification': u'h', u'storeid': u'158'}]}
    output = []
    for item in d.items():
        for ID in item[1][0]['__value__']:
            output.append(int(ID['Id']))
    
    print(output)
    

    输出

    [9624, 41822, 38916, 49462]
    

    【讨论】:

    • 感谢您如此迅速地回复我。我试过你的建议,它只返回我数据中的前 4 个 Id 值。我认为“]}”是正确的。
    猜你喜欢
    • 2013-11-18
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 2017-03-29
    • 2021-04-19
    • 1970-01-01
    • 2022-10-07
    相关资源
    最近更新 更多