Handling missing keys with Python's defaultdict


Python tip:

You can use defaultdict to provide a default value for missing keys when accessing or assigning:

defaultdict(default_factory)

default_factory is a function used to initialize the value for the missing key (None is set by default).

If you pass the list constructor as the default_factory, a defaultdict is created with the values that are list.

For example:

import json
from collections import defaultdict

products = [
    {"name": "Cold beer", "price": 3.5, "category": "Beer"},
    {"name": "Coffee", "price": 1.5, "category": "Warm drinks"},
    {"name": "Cappuccino", "price": 2.0, "category": "Warm drinks"},
    {"name": "Chicken Sandwich", "price": 3.5, "category": "Snacks"},
    {"name": "Vegan Sandwich", "price": 3.5, "category": "Snacks"},
]

products_by_group = defaultdict(list)

for product in products:
    products_by_group[product["category"]].append(product)

print(json.dumps(products_by_group, indent=2))

"""
{
  "Beer": [
    {
      "name": "Cold beer",
      "price": 3.5,
      "category": "Beer"
    }
  ],
  "Warm drinks": [
    {
      "name": "Coffee",
      "price": 1.5,
      "category": "Warm drinks"
    },
    {
      "name": "Cappuccino",
      "price": 2.0,
      "category": "Warm drinks"
    }
  ],
  "Snacks": [
    {
      "name": "Chicken Sandwich",
      "price": 3.5,
      "category": "Snacks"
    },
    {
      "name": "Vegan Sandwich",
      "price": 3.5,
      "category": "Snacks"
    }
  ]
}
"""