Python:从嵌套字典中提取数据

时间:2021-05-29 04:52:06

标签: python dictionary

我下载了一些返回字典的数据,我在下面提供了一个示例。我认为它可能是一个嵌套字典,但它看起来并不像一个。 (我是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]

3 个答案:

答案 0 :(得分: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]

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

答案 1 :(得分:1)

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

print(my_dict[temp])

答案 2 :(得分:0)

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

使用特定键提取值

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

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]