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'}]