Skip to content

    Dictionaries & Sets

    Python · Beginner

    Definition

    A dict maps keys to values; a set stores unique items. Both use hashing for fast lookup.

    Essential for counting, grouping and de-duplication.

    Diagram

    'a' → 3'b' → 1set {1, 2, 3}

    Flowchart

    Create dict or setInsert keyLook up in O(1)Iterate keys/items

    Example: Count words

    from collections import Counter
    print(Counter('a b a c a'.split()).most_common(1))

    Output: [('a', 3)]

    Complexity

    Insert/lookup O(1) average

    Key points

    • dict.get(k, default) avoids KeyError
    • defaultdict auto-creates values

    Interview questions

    Are dicts ordered?

    Yes, since Python 3.7 they keep insertion order.

    More Python topics