Skip to content

Instantly share code, notes, and snippets.

@stekern
Created August 10, 2020 14:38
Show Gist options
  • Save stekern/722ddb3b1d20205ea3428088f2c26ac7 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3.7
#
# Copyright (C) 2020 Erlend Ekern <dev@ekern.me>
#
# 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