0

Sorry for the post if it seems redundant. I've looked through a bunch of other posts and I can't seem to find what i'm looking for - perhaps bc I'm a python newby trying to write basic code...

Given a dictionary of any size: Some keys have a single value, others have a nested dictionary as its value.

I would like to convert the dictionary into a list (including the nested values as list items) but in a specific order.

for example:

d = {'E':{'e3': 'Zzz', 'e1':'Xxx', 'e2':'Yyy'}, 'D': {'d3': 'Vvv', 'd1':'Nnn', 'd2':'Kkk'}, 'U': 'Bbb'}

and I would like it to look like this:

order_list = ['U', 'D', 'E'] # given this order...

final_L = ['U', 'Bbb', 'D', 'd1', 'Nnn', 'd2', 'Kkk', 'd3', 'Vvv', 'E', 'e1', 'Xxx', 'e2', 'Yyy', 'e3', 'Zzz']

I can make the main keys fall into order but the the nested values. Here's what i have so far...

d = {'E':{'e3': 'Zzz', 'e1':'Xxx', 'e2':'Yyy'}, 'D': {'d3': 'Vvv', 'd1':'Nnn', 'd2':'Kkk'}, 'U': 'Bbb'}

order_list = ['U', 'D', 'E']

temp_list = []



for x in order_list:
    for key,value in d.items():
        if key == x:
            temp_list.append([key,value])

final_L = [item for sublist in temp_list for item in sublist]
print(final_L)

My current output is:

['U', 'Bbb', 'D', {'d1': 'Nnn', 'd2': 'Kkk', 'd3': 'Vvv'}, 'E', {'e1': 'Xxx', 'e3': 'Zzz', 'e2': 'Yyy'}]
virgiliocyte
  • 175
  • 3
  • 12

1 Answers1

0

So there a couple of easy transformation to make with a list comprehension:

>>> [(k, sorted(d[k].items()) if isinstance(d[k], dict) else d[k]) for k in 'UDE']
[('U', 'Bbb'),
 ('D', [('d1', 'Nnn'), ('d2', 'Kkk'), ('d3', 'Vvv')]),
 ('E', [('e1', 'Xxx'), ('e2', 'Yyy'), ('e3', 'Zzz')])]

Now you just need to flatten an arbitrary depth list, here's a post describing how to do that:

import collections
def flatten(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, str):
            yield from flatten(e)
        else:
            yield el

>>> list(flatten((k, sorted(d[k].items()) if isinstance(d[k], dict) else d[k]) for k in 'UDE'))
['U', 'Bbb', 'D', 'd1', 'Nnn', 'd2', 'Kkk', 'd3', 'Vvv', 'E', 'e1', 'Xxx', 'e2', 'Yyy', 'e3', 'Zzz']
Community
  • 1
  • 1
AChampion
  • 29,683
  • 4
  • 59
  • 75