How to Transform a List of Dictionaries with Sets in Python

Normalize a list of dict records — cleaning names, extracting unique tags with sets, and building a standardized result.

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

Python code

55 lines
Python 3.9+
def transform_data(raw_records):
    """Transform a list of dict records into normalized data with sets for unique values."""
    normalized = []
    unique_names = set()
    all_tags = set()
    
    for record in raw_records:
        # Normalize name to lowercase and strip whitespace
        name = record.get("name", "").strip().lower()
        
        # Only keep records that have a name
        if not name:
            continue
            
        # Extract and clean tags, skipping empty ones
        tags = {tag.strip().lower() for tag in record.get("tags", []) if tag.strip()}
        all_tags.update(tags)
        
        # Build a normalized record
        normalized.append({
            "id": record.get("id"),
            "name": name,
            "tags": tags,
            "active": record.get("active", False)
        })
        
        # Track unique names
        unique_names.add(name)
    
    # Add transformation summary
    result = {
        "records": normalized,
        "unique_names": len(unique_names),
        "all_tags": all_tags,
        "tags_count": len(all_tags),
        "total_records": len(normalized)
    }
    
    return result


if __name__ == "__main__":
    sample_data = [
        {"id": 1, "name": "Alice", "tags": ["Python", "Data"]},
        {"id": 2, "name": "Bob", "tags": ["SQL", "python"]},
        {"id": 3, "name": "  alice  ", "tags": ["ML"]},
        {"id": 4, "name": "", "tags": []},
        {"id": 5, "name": "Carol", "tags": ["Python", "Web"]}
    ]
    
    result = transform_data(sample_data)
    print(f"Total records: {result['total_records']}")
    print(f"Unique names: {result['unique_names']}")
    print(f"All tags: {sorted(result['all_tags'])}")
    print(f"Records: {result['records']}")

Output

stdout
Total records: 4
Unique names: 3
All tags: ['data', 'ml', 'python', 'sql', 'web']
Records: [{'id': 1, 'name': 'alice', 'tags': {'python', 'data'}, 'active': False}, {'id': 2, 'name': 'bob', 'tags': {'sql', 'python'}, 'active': False}, {'id': 3, 'name': 'alice', 'tags': {'ml'}, 'active': False}, {'id': 5, 'name': 'carol', 'tags': {'python', 'web'}, 'active': False}]

How it works

The function starts by normalizing each record — stripping and lowercasing the name, then skipping records with an empty name. Tags are cleaned similarly and stored in a set, which automatically deduplicates them. Using record.get() with defaults avoids key errors on sparse data. Sets are ideal here for tracking unique names and unique tags, and update() adds multiple elements efficiently. The final result bundles the normalized records with summary counts, making it easy to inspect the transformation.

Common mistakes

  • Forgetting to strip whitespace before checking if a name is empty, leading to records with ' ' being kept.
  • Reusing a single set for all_tags inside the loop instead of calling update() on an outer set.
  • Assuming tags order matters — sets are unordered, so sort before printing if order is needed.
  • Not using .get() with defaults, causing KeyError on missing keys.

Variations

  1. Use a list comprehension with filtering and map() for a more functional style on simple cases.
  2. Return a pandas DataFrame instead of a dict for downstream analytics.

Real-world use cases

  • Cleaning user-submitted form data — lowercasing emails and collecting unique interest tags.
  • Aggregating multi-source logs into normalized events while deduplicating error types.
  • Preparing product catalog entries with unique category sets for a recommendation engine.

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.