Data append in a list using the previous data in Python

İ need to create a list in Python. It is a little complicated. The list will contain items which appends according to previous value. For example, suppose that my list contains

x : 11 (key, value pair)
y : 5
z : 6

if I want to add another "x" item with value "4", it will detect the previous value "11" of "x" and it will be recorded as " x : 15" as the sum with the previous one. I thought that I might use linked lists but I could not figure it out. Can you just provide me with other methods, data structures or code for this purpose?


L = [{'x':11}, {'y':2}, {'z':3}]

def addItem(L, key, value):
    for index, element in enumerate(L):
        if key in element:
            L.insert(index, {key, element[key] + value})        
    return L

L[:] = addItem(L, 'x', 4)

Using the defaultdict and calling a function:

from collections import defaultdict

def add_item(d, key, value):
    d[key] += value

d = defaultdict(int)
add_item(d, 'x', 11)
add_item(d, 'x', 4)
print d
defaultdict(<type 'int'>, {'x': 15})

Need Your Help

How to draw 32-bit alpha channel bitmaps?

mfc alphablending bmp

I need to create a custom control to display bmp images with alpha channel. The background can be painted in different colors and the images have shadows so I need to truly "paint" the alpha channe...

Passing variable through pages in WordPress

php jquery wordpress variables

I have a WordPress project on in which I need to pass a variable from one page to another.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.