Sumeeth Sumeeth - 3 years ago 186
Python Question

List of lists in python

If I am given two list of lists such as follows:

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

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


I want a list as follows:

final = [['John',4],
['Smith',7],
['Kapil',3],
['Stephen',3]]


which will contain the sum of the numbers if the name has occurred in both list1 and list2.

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download