Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (16.4k points)

I'm having Python 2.7 in my system. I'm also trying to de-deuplicate a lit of lists and join the values of the duplicates. Let my list be:

original_list = [['a', 1], ['b', 1], ['a', 1], ['b', 1], ['b', 2], ['c', 2], ['b', 3]]

I need to coordinate on the principal component of each settled rundown and afterward add the estimations of the subsequent component. I need to wind up with this (the request for the last rundown doesn't make a difference):

ideal_output = [['a', 2], ['b', 7], ['c', 2]]

Look at the following code, which will find the duplicate values based on the first element of each nested list:

for item in original_list:

    matches = -1

    for x in original_list:

        if (item[0] == x[0]):

            matches += 1

    if matches >= 1: 

        if item[0] not in duplicates_list:


Can anyone suggest what would be the best way to find the duplicates?

1 Answer

0 votes
by (26.4k points)

Look at the following code:

totals = {}

for k,v in original_list:

  totals[k] = totals.get(k,0) + v

# totals = {'a': 2, 'c': 2, 'b': 7

Once when you a dictionary like that, then you can use items function to get a list of tuples:


# => [('a', 2), ('c', 2), ('b', 7)]

Later, just map the list accross the tuples to get a list of lists:

map(list, totals.items())

# => [['a', 2], ['c', 2], ['b', 7]]

If you need them in order, just sort them:

sorted(map(list, totals.items()))

# => [['a', 2], ['b', 7], ['c', 2]]

Want to learn more about python? Come and join: python training course

Related questions

Browse Categories