【问题标题】:How to optimised the conversion of nested into flat level dictionary in Python? [duplicate]如何优化 Python 中嵌套到平面级字典的转换? [复制]
【发布时间】:2020-10-28 11:28:54
【问题描述】:

目标是转换下面的嵌套字典

secondary_citing_paper = [{"paper_href": 'Unique One', 'Paper_year': 1}, \
                          {"paper_href": 'Unique Two', 'Paper_year': 2}]
inner_level = [secondary_citing_paper, secondary_citing_paper]
my_dict_x = [inner_level, inner_level]

到Python中的平级字典(对不起,这里的术语使用得更好!),如下

expected_output = [{"paper_href": 'Unique One', 'Paper_year': 1}, \
                   {"paper_href": 'Unique Two', 'Paper_year': 2}, \
                   {"paper_href": 'Unique One', 'Paper_year': 1}, \
                   {"paper_href": 'Unique Two', 'Paper_year': 2}, \
                   {"paper_href": 'Unique One', 'Paper_year': 1}, \
                   {"paper_href": 'Unique Two', 'Paper_year': 2}, \
                   {"paper_href": 'Unique One', 'Paper_year': 1}, \
                   {"paper_href": 'Unique Two', 'Paper_year': 2}, \
                   ]

以下代码已起草

expected_output = []
for my_dict in my_dict_x:
    for the_ref in my_dict:
        for x_ref in the_ref:
            expected_output.append( x_ref )

虽然代码服务于它的目的,但我想知道是否存在更多 Pythonic 方法?

请注意,我在 SO 上发现了几个问题,但它是关于恰好合并 2 个字典。

编辑: 由于与类似问题相关,该主题已关闭,我无法删除该主题,因为 Vishal Singh 已发布他的建议。

不过,根据OP 的建议,递归转换的一种方法如下

def flatten(container):
    for i in container:
        if isinstance(i, (list,tuple)):
            yield from flatten(i)
        else:
            yield i


expected_output=list(flatten(my_dict_x))

或更快的iteration approach

def flatten(items, seqtypes=(list, tuple)):
    for i, x in enumerate(items):
        while i < len(items) and isinstance(items[i], seqtypes):
            items[i:i+1] = items[i]
    return items

expected_output = flatten(my_dict_x[:])

【问题讨论】:

    标签: python performance dictionary


    【解决方案1】:

    您的代码的更 Python 版本将如下所示

    expected_output = [
        x_ref
        for my_dict in my_dict_x
        for the_ref in my_dict
        for x_ref in the_ref
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-14
      • 2023-03-11
      • 1970-01-01
      • 2018-07-13
      • 2016-06-16
      • 1970-01-01
      • 2011-07-05
      • 2019-02-04
      相关资源
      最近更新 更多