How to optimised the conversion of nested into flat level dictionary in Python? [duplicate]

冷暖自知 提交于 2021-01-29 22:31:40

问题


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]

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}, \
                   ]

The following code was drafted

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 )

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

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

Edit: 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.

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

or faster 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[:])

回答1:


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
]


来源:https://stackoverflow.com/questions/62788260/how-to-optimised-the-conversion-of-nested-into-flat-level-dictionary-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!