如何从嵌套的有序字典中获取所有键

时间:2019-10-16 13:06:53

标签: python

递归地从Ordered字典中提取所有键

我尝试使用一些在线可用的递归函数,但可以得到我想要的。

输入的有序字典采用以下值

input = OrderedDict([('report',
              OrderedDict([('generated_at', '2019-07-01 05:07:13'),
                           ('record_count', 23),
                           ('start_date', '2019-02-10'),
                           ('end_date', '2019-02-10'),
                           ('records',
                            [OrderedDict([('_data_type', 'PREGNANT'),
                                          ('_app_type', 'DAYS_POST')]),
                             OrderedDict([('_data_type', 'VISION'),
                                          ('_app_type', 'DAYS_PRE')])])]))])

期望的输出是包括嵌套在内的所有键的列表。

['generated_at','record_count','start_date','end_date','_data_type','_app_type']

订单必须按照上面指定的顺序。

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

from collections import OrderedDict

ipt = OrderedDict([('report',
                    OrderedDict([('generated_at', '2019-07-01 05:07:13'),
                                 ('record_count', 23),
                                 ('start_date', '2019-02-10'),
                                 ('end_date', '2019-02-10'),
                                 ('records',
                                  [OrderedDict([('_data_type', 'PREGNANT'),
                                                ('_app_type', 'DAYS_POST')]),
                                   OrderedDict([('_data_type', 'VISION'),
                                                ('_app_type', 'DAYS_PRE')])])]))])


def nested(od):
    """Iterates over nested OrderedDict returning nested keys"""
    if isinstance(od, OrderedDict):
        for k, value in od.items():
            yield k
            if isinstance(value, (list, OrderedDict)):
                yield from nested(value)
    if isinstance(od, list):
        for value in od:
            if isinstance(value, (list, OrderedDict)):
                yield from nested(value)


# iterate over the keys, store no duplicates, preserver order of appearance
result, seen = [], set()
for key in nested(ipt['report']):
    if key not in seen:
        result.append(key)
        seen.add(key)

print(result)

输出

['generated_at', 'record_count', 'start_date', 'end_date', 'records', '_data_type', '_app_type']