FacundoGFlores
FacundoGFlores

Reputation: 8118

Python - Group by over dicts

I am using Python 3.5 and I have the following array of dics:

d1 = [{id=1, col="name", oldvalue="foo", newvalue="bar"}, {id=1, col="age", oldvalue="25", newvalue="26"}, {id=2, col="name", oldvalue="foo", newvalue="foobar"}, {id=3, col="age", oldvalue="25", newvalue="26"}]

d2 = [{id=1, col="name", oldvalue="foo", newvalue="bar"}, {id=1, col="age", oldvalue="25"]

d3 = [{id=3, col="age", oldvalue="25", newvalue="26"}]

As you can see it is showing some changes made to particular "rows".

I want to know if there is a way to return the total of rows updated, so:

def counting_updates(d):
    # ...
    return total

print counting_updates(d1) # prints 3 because 3 rows were updated
print counting_updates(d2) # prints 1 because 1 row was updated
print counting_updates(d3) # prints 1 because 1 row was updated

Upvotes: 0

Views: 48

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 61032

If you're looking for the number of unique ids, then

len({row['id'] for row in d})

The {} is a set comprehension.

Upvotes: 1

Related Questions