Python add numbers in a list
Question: Anyone can help me with these? Basically I have list begin created as shown
below:

    
    
    >>> item
    [('apple', 7, 'population'), ('apple', 9, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')]
    

I want to combine the result of the object only when such as apple and
population is met. This is my end result that I want:

    
    
    >>> item
    [('apple', 16, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')]
    

Any help will be appreciated.

My fault if the question wasn't clear: This is some of my code.

    
    
    def add(par):
        temp_dict = {}
        for name, count, term in par:
                if name in temp_dict:
                        temp_dict[name] += count
                else:
                        temp_dict[name] = count
        result = []
        for name, count, term in par:
                if name in temp_dict:
                        result.append((name, temp_dict[name], term)) 
                        del temp_dict[name]
        return result
    

How can I make ammendment to the class so that, it returns the desired result?
The code above still adds the "apple" together, which is this:

> > > item [('apple', 19, 'disease'), ('orange', 6, 'population')]


Answer: You may achieve the desired result as follows:

    
    
    In [6]: my_items = [('apple', 7, 'population'), ('apple', 9, 'population'), ('apple', 3, 'disease'), ('orange', 6, 'population')]
    
    In [7]: import collections
    
    In [8]: my_counter = collections.defaultdict(int)
    
    In [9]: for i in my_items:
        # at this point, i is a tuple, let's unpack it
        (fruit, n, category) = i
        # use the tuple (fruit, category) as a key.
        # note that this has to be a tuple, and not a list
        my_counter[(fruit, category)] += n
       ...:
    
    In [10]: my_counter
    Out[10]: defaultdict(<class 'int'>, {('orange', 'population'): 6, ('apple', 'population'): 16, ('apple', 'disease'): 3})
    

(note that this is an [IPython](http://ipython.org/) session I highly
recommend it over the vanilla shell for interactive work)

In this example, `my_counter` is a modified `dict` object. It differs from the
"regular" `dict` by the fact that if the specified key isn't available, a
default value will be automatically created (in our case -- integer zero).
From your example I understand that you are new to Python. If you need more
aggregation power for large data amounts, you may want to take a look at
[Pandas](http://pandas.pydata.org/).

Good luck.

**EDIT** For the sake of completeness, following
[keimina](http://stackoverflow.com/users/2931409/keimina)'s [answer in this
thread](http://stackoverflow.com/a/24930626/17523), you might consider using
`collections.Counter` that has many [features that are useful for
counters](http://stackoverflow.com/a/19883180/17523) such as `most_common()`
function that was new for me.

