How to Count Co-occurrence Pairs in Python with Nested Dictionaries

This code counts how often any two items appear together in the same group, using a nested defaultdict keyed by item pairs.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 12 views 0 copies

Python code

19 lines
Python 3.9+
from itertools import combinations
from collections import defaultdict

def count_cooccurrences(items_per_group):
    cooccurrence = defaultdict(lambda: defaultdict(int))
    for group in items_per_group:
        for a, b in combinations(sorted(group), 2):
            cooccurrence[a][b] += 1
            cooccurrence[b][a] += 1
    return {k: dict(v) for k, v in cooccurrence.items()}

if __name__ == "__main__":
    transactions = [
        ["milk", "bread", "eggs"],
        ["bread", "butter"],
        ["milk", "bread", "butter"]
    ]
    result = count_cooccurrences(transactions)
    print(result)

Output

stdout
{'milk': {'bread': 2, 'eggs': 1, 'butter': 1}, 'bread': {'milk': 2, 'eggs': 1, 'butter': 2}, 'eggs': {'milk': 1, 'bread': 1}, 'butter': {'bread': 2, 'milk': 1}}

How it works

defaultdict(lambda: defaultdict(int)) builds a two-level dictionary where missing keys default to an int counter, so increments never raise a KeyError. Sorting each group before combinations ensures that only one order of a pair is considered, yet the code still records both directions for easy lookups. The outer defaultdict is converted to a normal dict at the end for cleaner printing.

Common mistakes

  • Forgetting to sort the group before combinations, leading to duplicate pairs counted inconsistently
  • Using a single-level dict and manually checking keys, missing pairs when one item appears in many contexts

Variations

  1. Use a dict of dicts with setdefault(key, {}).setdefault(pair, 0) instead of defaultdict.
  2. Combine with pandas.crosstab when working on larger datasets with pandas.

Real-world use cases

  • Building a recommendation engine by counting items bought together from purchase transactions.
  • Analyzing word co-occurrences in text for topic modeling or NLP feature extraction.
  • Detecting frequent patterns in log events to identify correlated failures in a system.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.