0

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[:])
mpx
  • 3,081
  • 2
  • 26
  • 56

1 Answers1

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
]
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33