Home:ALL Converter>How to simplify a dictionary of nested lists in python?

How to simplify a dictionary of nested lists in python?

Ask Time:2016-04-17T07:19:57         Author:nachocab

Json Formatter

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

Author:nachocab,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/36670914/how-to-simplify-a-dictionary-of-nested-lists-in-python
Francisco :

from collections import OrderedDict\n\nret = OrderedDict()\nfor order in correct_order:\n for key, value in dict_with_nested_list[order]:\n if key not in ret:\n ret[key] = []\n ret[key].append(value)\n\nprint [[key] + value for key, value in ret.items()]\n",
2016-04-16T23:30:08
TigerhawkT3 :

I highly recommend keeping some kind of dictionary structure, with a list for each value. You can convert it into another structure later, if you want.\n\n>>> import collections\n>>> dict_with_nested_list = {\n... 'B': [['a', 2], ['b', 4]],\n... 'A': [['a', 1], ['b', 3]]\n... }\n>>> result = collections.defaultdict(list)\n>>> for l in dict_with_nested_list.values():\n... for k,v in l:\n... result[k].append(v)\n...\n>>> result = {k:sorted(v) for k,v in result.items()}\n>>> result\n{'b': [3, 4], 'a': [1, 2]}\n>>> sorted(result.items())\n[('a', [1, 2]), ('b', [3, 4])]\n>>> [[k]+v for k,v in sorted(result.items())]\n[['a', 1, 2], ['b', 3, 4]]\n",
2016-04-16T23:28:46
yy