如何在Python中优化嵌套到平面词典的转换? [英] How to optimised the conversion of nested into flat level dictionary in Python?

查看:39
本文介绍了如何在Python中优化嵌套到平面词典的转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是转换以下嵌套词典

The objective is to convert the following nested dictionary

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中的平面词典中(很抱歉,这里的术语使用得更好!),如下所示

into a flat level dictionary in Python (sorry for the better use of terminology here!), as below

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 )

虽然代码达到了目的,但是我想知道是否存在更多的Python方法?

While the code serve its purpose, but I wonder if there exist more Pythonic approach?

请注意,我在SO上发现了几个问题,但这与准确地合并2个字典有关.

Note I found several question on SO but its about merging exactly 2 dictionaries.

由于存在类似问题,该话题已经关闭,我无法删除该话题,因为Vishal Singh发表了他的建议.

The thread has been closed due to associated with a similar question, and I am unable delete this thread as Vishal Singh has post his suggestion.

不过,按照 OP 的建议,递归转换的一种方法如下所示:

Nevertheless, as per suggested by OP, one way to recursively convert is as below

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))

或更快的迭代方法

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版本越多,它的外观将越像这样

the more pythonic version of your code will look like this

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

这篇关于如何在Python中优化嵌套到平面词典的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆