Using the program below, even if you have several records, and not just two for one key, it will work
#!/usr/local/bin/python3 myList = [(0,2),(1,3),(2,4),(0,5),(1,6),(1,2)] h = {} c = {} sum = 0 for k in myList: # if key value already present if k[0] in c: if k[0] in h: sum = sum - h[k[0]] h[k[0]] = h[k[0]] * k[1] else: h[k[0]] = c[k[0]] * k[1] sum = sum + h[k[0]] else: # stores key and value if first time though the loop c[k[0]] = k[1] print('sum is' + str(sum))
user966588
source share