nachocab nachocab - 1 year ago 56
Python Question

How to simplify a dictionary of nested lists in python?

I currently have this dictionary with nested lists:

dict_with_nested_list = {
'B': [['a', 2], ['b', 4]],
'A': [['a', 1], ['b', 3]]

correct_order = ['A', 'B']

I'm trying to simplify it, so that each nested list is in the correct order and its elements are the key and its corresponding values:

desired_output = [
['a', 1, 2],
['b', 3, 4]

Answer Source
from collections import OrderedDict

ret = OrderedDict()
for order in correct_order:
    for key, value in dict_with_nested_list[order]:
        if key not in ret:
            ret[key] = []

print [[key] + value for key, value in ret.items()]