Created
August 10, 2020 14:38
-
-
Save stekern/722ddb3b1d20205ea3428088f2c26ac7 to your computer and use it in GitHub Desktop.
Using Pythons's reduce function to group a list of dictionaries by a specific key
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
#!/usr/bin/env python3.7 | |
# | |
# Copyright (C) 2020 Erlend Ekern <[email protected]> | |
# | |
# Distributed under terms of the MIT license. | |
""" | |
An example of using `functools.reduce` to group a list of dictionaries by a specific key. | |
""" | |
from functools import reduce | |
purchases = [ | |
{"customer_id": "0", "product_id": "0"}, | |
{"customer_id": "0", "product_id": "1"}, | |
{"customer_id": "1", "product_id": "2"}, | |
{"customer_id": "2", "product_id": "2"}, | |
{"customer_id": "0", "product_id": "3"}, | |
] | |
group_by_key = "customer_id" | |
group_purchases_by_key = reduce( | |
lambda acc, curr: { | |
**acc, | |
curr[group_by_key]: acc.get(curr[group_by_key], []) + [curr], | |
}, | |
purchases, | |
{}, | |
) | |
print(group_purchases_by_key) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment