我目前有这本带嵌套列表的字典:
dict_with_nested_list = {
'B': [['a', 2], ['b', 4]],
'A': [['a', 1], ['b', 3]]
}
correct_order = ['A', 'B']
我试图简化它,以便每个嵌套列表都按正确的顺序排列,并且它的元素是键及其对应的值:
desired_output = [
['a', 1, 2],
['b', 3, 4]
]
最佳答案
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] = []
ret[key].append(value)
print [[key] + value for key, value in ret.items()]
关于python - 如何简化 python 中的嵌套列表字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36670914/