Created
February 9, 2017 13:59
-
-
Save oleksmarkh/9b0ed87233917503ef04fb30b11480c2 to your computer and use it in GitHub Desktop.
groups values applying an aggregation function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
table = [ | |
{'age': 32, 'gender': 'm', 'country': 'Germany', 'transactions': 4233}, | |
{'age': 23, 'gender': 'f', 'country': 'US', 'transactions': 11223}, | |
{'age': 31, 'gender': 'f', 'country': 'France', 'transactions': 3234}, | |
{'age': 41, 'gender': 'm', 'country': 'France', 'transactions': 2230}, | |
{'age': 19, 'gender': 'm', 'country': 'Germany', 'transactions': 42}, | |
{'age': 21, 'gender': 'f', 'country': 'France', 'transactions': 3315}, | |
{'age': 23, 'gender': 'm', 'country': 'Italy', 'transactions': 520} | |
] | |
def group_aggregate(groupby, field, agg, table): | |
grouped = dict() | |
for row in table: | |
groupby_value = row.get(groupby) | |
field_value = row.get(field) | |
grouped[groupby_value] = agg([grouped[groupby_value], field_value]) if grouped.get(groupby_value) else field_value | |
for k, v in grouped.items(): | |
print("{}: {}".format(k, v)) | |
# SELECT SUM(transactions) FROM table GROUP BY gender | |
# | |
# m: 7025 | |
# f: 17772 | |
group_aggregate(groupby='gender', | |
field='transactions', | |
agg=sum, | |
table=table) | |
# SELECT MAX(age) FROM table GROUP BY country | |
# | |
# Italy: 23 | |
# France: 41 | |
# US: 23 | |
# Germany: 32 | |
group_aggregate(groupby='country', | |
field='age', | |
agg=max, | |
table=table) | |
# SELECT MAX(age) FROM table GROUP BY gender | |
# | |
# m: 19 | |
# f: 21 | |
group_aggregate(groupby='gender', | |
field='age', | |
agg=min, | |
table=table) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment