【问题标题】:Python: Extracting data from nested dictionaryPython:从嵌套字典中提取数据
【发布时间】:2021-05-29 04:52:06
【问题描述】:

我已经下载了一些返回字典的数据,我在下面提供了一个示例。我认为它可能是一个嵌套字典,但它看起来并不像一个。 (我是 python 新手) 我不明白这本词典的结构以及如何从中提取数据。 我想提取给定键的值。所以首先,返回值key = 'id'

这是示例字典和我尝试使用的一种代码:

 my_dict = {'id': 5729283,
 'title': 'Auto & Transport(L1)',
 'colour': None,
 'is_transfer': None,
 'is_bill': None,
 'refund_behaviour': None,
 'children': [{'id': 5698724,
   'title': 'Car Insurance',
   'colour': None,
   'is_transfer': False,
   'is_bill': True,
   'refund_behaviour': 'credits_are_refunds',
   'children': [],
   'parent_id': 5729283,
   'roll_up': False,
   'created_at': '2019-07-25T12:38:46Z',
   'updated_at': '2021-01-19T08:12:28Z'},
  {'id': 5729295,
   'title': 'Toll',
   'colour': None,
   'is_transfer': False,
   'is_bill': False,
   'refund_behaviour': None,
   'children': [],
   'parent_id': 5729283,
   'roll_up': False,
   'created_at': '2019-08-05T04:30:55Z',
   'updated_at': '2021-01-08T02:33:11Z'}],
 'parent_id': None,
 'roll_up': True,
 'created_at': '2019-08-05T04:28:04Z',
 'updated_at': '2021-01-08T02:44:09Z'}


temp = 'id'
[val[temp] for key, val in my_dict.items() if temp in val]

【问题讨论】:

  • 您只是想提取键 'id' 的值还是想提取其他一些值?我只是想知道你为什么要这么做[val[temp] for key, val in my_dict.items() if temp in val]
  • 是否要在子列表中查找值?
  • 是的,我也想提取其他值。我使用该代码是因为我认为它是一个嵌套字典,而这就是我找到的用于搜索嵌套字典的代码。虽然现在我不这么认为

标签: python dictionary


【解决方案1】:

虽然已经选择了答案,但请允许我本着分享的精神提出以下建议。下面使用递归函数的代码可以在嵌套字典或“字典列表”中使用特定键提取值

您确实必须分析字典/列表的嵌套结构。只需指定键,该函数将提取与键配对的所有值。

my_dict = {...blah...}

def get_vals(nested, key):
    result = []
    if isinstance(nested, list) and nested != []:   #non-empty list
        for lis in nested:
            result.extend(get_vals(lis, key))
    elif isinstance(nested, dict) and nested != {}:   #non-empty dict
        for val in nested.values():
            if isinstance(val, (list, dict)):   #(list or dict) in dict
                result.extend(get_vals(val, key))
        if key in nested.keys():   #key found in dict
            result.append(nested[key])
    return result

get_vals(my_dict, 'id')

输出

[5698724, 5729295, 5729283]

【讨论】:

    【解决方案2】:

    结构看起来像一棵树。您有一个 ID 为 5729283 的根节点,然后是 children 的列表,它们本身有零个或多个子节点(ID 为 56987245729295)。

    处理此问题的常用方法是递归函数(或生成器)。该函数产生根值,然后递归处理子代:

    def getKey(d, key):
        yield d[key]                       # the root element
        for child in d['children']:
            yield from getKey(child, key)  # the same for children
    
    temp = 'id'
          
    list(getKey(my_dict, temp))
    # [5729283, 5698724, 5729295]
    

    这将执行树的深度优先遍历(尽管如果它只有一个级别的子级,这并不重要)。

    【讨论】:

      【解决方案3】:

      提取temp = 'id'的值 你可以这样做

      print(my_dict[temp])

      【讨论】:

      • 令人惊讶的是(对我来说)它确实有效。但我的实际情况更复杂。
      • 我将更新答案以提取所有值。
      猜你喜欢
      • 2021-08-24
      • 2021-02-12
      • 2018-04-20
      • 1970-01-01
      • 2021-10-29
      • 2023-03-20
      • 2016-05-15
      • 2021-04-19
      • 1970-01-01
      相关资源
      最近更新 更多