[Solved] List of lists in python [duplicate]


A simple way to do this is to use a dictionary. Something like this:

list1 = [['John',2],['Smith',5],['Kapil',3]]

list2 = [['Smith',2],['John',2],['Stephen',3]]

dict = {}

for item in list1:
    try:
        dict[item[0]] += item[1]
    except:
        dict[item[0]] = item[1]

for item in list2:
    try:
        dict[item[0]] += item[1]
    except:
        dict[item[0]] = item[1]

print dict

This gives the output:

{'John': 4, 'Smith': 7, 'Kapil': 3, 'Stephen': 3}

Then turn it into a list of lists, with the following:

results = []
for k, v in dict.items():
    results.append([k, v])

print results
# [['John', 4], ['Smith', 7], ['Kapil', 3], ['Stephen', 3]]

Here’s a reusable function for multiple lists:

list1 = [['John',2],['Smith',5],['Kapil',3]]
list2 = [['Smith',2],['John',2],['Stephen',3]]
list3 = [['Smith',7],['John',5],['Kapil',33]]

def sort_lists(*args):
    dict = {}
    for arg in args:
        for item in arg:
            try:
                dict[item[0]] += item[1]
            except:
                dict[item[0]] = item[1]
    results = []
    for k, v in dict.items():
        results.append([k, v])

    return results

print sort_lists(list1, list2, list3)

1

solved List of lists in python [duplicate]