Skip to main content
 首页 » 编程设计

python之如何简化 python 中的嵌套列表字典

2025年05月04日12shangdawei

我目前有这本带嵌套列表的字典:

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