How to match two values ​​in dict and merge results

Say I have data with timestamps, prices, and amounts. This data can be quite large, and matching conditions can occur anywhere in the group. A simple example shown below:

[{"date":1387496043,"price":19.379,"amount":1.000000}
{"date":1387496044,"price":20.20,"amount":2.00000}
{"date":1387496044,"price":10.00,"amount":0.10000}
{"date":1387496044,"price":20.20,"amount":0.300000}]

How can I sort this to combine the sums of any item with the same timestamp and the same price?

So, the results look like this (note that the sums of the sums of 2.0 and 0.3 are summarized):

[{"date":1387496043,"price":19.379,"amount":1.000000}
{"date":1387496044,"price":20.20,"amount":2.30000}
{"date":1387496044,"price":10.00,"amount":0.10000}]

I tried some confusing methods (using Python 2.7.3), but I don't know python very well. I am sure there is a good way to find 2 matching values ​​and then update them with a new amount and remove the duplicate.

FYI Here are the test data

L=[{"date":1387496043,"price":19.379,"amount":1.000000},{"date":1387496044,"price":20.20,"amount":2.00000},{"date":1387496044,"price":10.00,"amount":0.10000},{"date":1387496044,"price":20.20,"amount":0.300000}]
+4
3

, - (, ) . , , .

def combine(L):
    results = {}
    for item in L:
        key = (item["date"], item["price"])
        if key in results:  # combine them
            results[key] = {"date": item["date"], "price": item["price"], "amount": item["amount"] + results[key]["amount"]}
        else:  # don't need to combine them
            results[key] = item
    return results.values()

O (n) , , , .

+1

FWIW :

records = [
    {"date":1387496043,"price":19.379,"amount":1.000000},
    {"date":1387496044,"price":20.20,"amount":2.00000},
    {"date":1387496044,"price":10.00,"amount":0.10000},
    {"date":1387496044,"price":20.20,"amount":0.300000},
]

import sqlite3
db = sqlite3.connect(':memory:')
db.row_factory = sqlite3.Row
db.execute('CREATE TABLE records (date int, price float, amount float)')
db.executemany('INSERT INTO records VALUES (:date, :price, :amount)', records)
sql = 'SELECT date, price, SUM(amount) AS amount FROM records GROUP BY date, price'
records = [dict(row) for row in db.execute(sql)]
print(records)
+1

Standard Access Based Approach

from collections import defaultdict
d = defaultdict(float)
z = [{"date":1387496043,"price":19.379,"amount":1.000000},
{"date":1387496044,"price":20.20,"amount":2.00000},
{"date":1387496044,"price":10.00,"amount":0.10000},
{"date":1387496044,"price":20.20,"amount":0.300000}]
for x in z:
    d[x["date"], x["price"]] += x["amount"]
print [{"date": k1, "price": k2, "amount": v} for (k1, k2), v in d.iteritems()] 
[{'date': 1387496044, 'price': 10.0, 'amount': 0.1},
{'date': 1387496044, 'price': 20.2, 'amount': 2.3},
{'date': 1387496043, 'price': 19.379, 'amount': 1.0}]
+1
source

All Articles