DEV Community

yongchang zhang
yongchang zhang

Posted on

Python Dictionaries and Sets: Clean Patterns for Grouping and Counting Data

Working with raw lists of logs, user events, or CSV rows in Python often boils down to three everyday tasks: removing duplicates, counting occurrences, and grouping related items together. While nested loops can get the job done, they quickly become slow and hard to read as data grows.

Python's built-in set and dict types—along with helpers from the collections module—give you O(1) average-time lookups and clean, expressive patterns. Here is how to use them effectively in real-world code.


1. Fast Deduplication While Preserving Order

A set automatically removes duplicates, though it does not guarantee order. When order matters (for example, keeping the first occurrence of each tag or user ID), you can combine a set for fast membership checks with a list, or use dict.fromkeys().

events = ["login", "view", "login", "click", "view", "purchase"]

# Order-preserving deduplication with dict.fromkeys() (Python 3.7+)
unique_events = list(dict.fromkeys(events))
print(unique_events)
# Output: ['login', 'view', 'click', 'purchase']
Enter fullscreen mode Exit fullscreen mode

If you need to deduplicate records by a specific field (like an email or user ID), track seen keys in a set:

users = [
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Bob"},
    {"id": 1, "name": "Alice (duplicate)"},
]

seen_ids = set()
unique_users = []

for user in users:
    if user["id"] not in seen_ids:
        seen_ids.add(user["id"])
        unique_users.append(user)

print(unique_users)
# Output: [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}]
Enter fullscreen mode Exit fullscreen mode

2. Counting Occurrences Without Boilerplate

Instead of writing if key in counts: checks manually, use dict.get() or collections.Counter.

Using dict.get()

words = ["python", "set", "dict", "python", "loop", "dict", "python"]
counts = {}

for word in words:
    counts[word] = counts.get(word, 0) + 1

print(counts)
# Output: {'python': 3, 'set': 1, 'dict': 2, 'loop': 1}
Enter fullscreen mode Exit fullscreen mode

Using collections.Counter

For most counting tasks, Counter is even cleaner and includes helpful methods like .most_common():

from collections import Counter

words = ["python", "set", "dict", "python", "loop", "dict", "python"]
word_counts = Counter(words)

print(word_counts.most_common(2))
# Output: [('python', 3), ('dict', 2)]
Enter fullscreen mode Exit fullscreen mode

3. Grouping Data with defaultdict

When you want to group items by a category—such as grouping orders by status or filenames by extension—collections.defaultdict(list) avoids repetitive key-initialization logic.

from collections import defaultdict

files = ["report.pdf", "notes.txt", "data.csv", "slides.pdf", "todo.txt"]
by_extension = defaultdict(list)

for filename in files:
    ext = filename.rsplit(".", 1)[-1]
    by_extension[ext].append(filename)

print(dict(by_extension))
# Output: {'pdf': ['report.pdf', 'slides.pdf'], 'txt': ['notes.txt', 'todo.txt'], 'csv': ['data.csv']}
Enter fullscreen mode Exit fullscreen mode

If you want each group to automatically deduplicate its items, swap list for set:

from collections import defaultdict

tags_by_post = [
    ("post_1", "python"),
    ("post_1", "tutorial"),
    ("post_1", "python"),
    ("post_2", "sets"),
]

grouped_tags = defaultdict(set)
for post_id, tag in tags_by_post:
    grouped_tags[post_id].add(tag)

print({k: sorted(v) for k, v in grouped_tags.items()})
# Output: {'post_1': ['python', 'tutorial'], 'post_2': ['sets']}
Enter fullscreen mode Exit fullscreen mode

4. Comparing Datasets Using Set Operations

Sets shine when you need to find overlaps or differences between two collections without writing nested loops:

yesterday_users = {"u101", "u102", "u103", "u104"}
today_users = {"u103", "u104", "u105"}

returning = yesterday_users & today_users
new_today = today_users - yesterday_users
churned = yesterday_users - today_users

print("Returning:", sorted(returning))  # ['u103', 'u104']
print("New today:", sorted(new_today))  # ['u105']
print("Churned:", sorted(churned))      # ['u101', 'u102']
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Use dict.fromkeys() or a seen set for O(n) order-preserving deduplication.
  • Use Counter or dict.get() to count frequencies cleanly.
  • Use defaultdict(list) or defaultdict(set) to group records by key.
  • Use set operators (&, -, |) to compare datasets in a single expression.

If you are looking for more structured, step-by-step guides across Python and other core programming topics, explore the free systematic programming tutorial library at HowCodex.

Top comments (0)