使用python中的列表列表合并字典

时间:2016-11-06 11:20:17

标签: python list dictionary

我正在使用以下代码:

dictio = {"Jesse": 6, "Maybel": 3, "Callie": 2, "Maggie": 5}  
cargo = [[6, 3], [5, 2]]  
def transport(dictio, cargo):      
    final = [ ]    
    for i in cargo:    
        for k,v in dictio.items():  
            for x in i:  
                if x==v:  
                    final.append(k)  
                print(final)
transport(dictio, cargo)

我的功能在一个列表中打印所有名称:

['Maybel', 'Jesse', 'Maggie', 'Callie']  

但这并不像预期的那样。我应该怎么做才能保持原始列表格式的名称,像这样?

[['Maybel', 'Jesse'], ['Maggie', 'Callie']]

1 个答案:

答案 0 :(得分:3)

通过创建适当的子列表:

dictio = {"Jesse": 6, "Maybel": 3, "Callie": 2, "Maggie": 5}
cargo = [[6, 3], [5, 2]]

final = []
for i in cargo:
    sub = []
    final.append(sub)
    for k, v in dictio.items():
        for x in i:
            if x == v:
                sub.append(k)
print(final)

输出:

[['Jesse', 'Maybel'], ['Maggie', 'Callie']]