All categories
    PythonAdvanced

    Collections Module

    Python collections module: Counter, defaultdict, namedtuple, and deque for powerful and efficient data structures.

    01Counter for tallies

    main.py
    from collections import Counter
    words = ["a", "b", "a", "c", "a", "b"]
    print(Counter(words))
    Output
    Counter({'a': 3, 'b': 2, 'c': 1})

    02defaultdict for counting

    main.py
    from collections import defaultdict
    d = defaultdict(int)
    for char in "hello":
        d[char] += 1
    print(dict(d))
    Output
    {'h': 1, 'e': 1, 'l': 2, 'o': 1}

    03namedtuple for records

    main.py
    from collections import namedtuple
    Point = namedtuple("Point", ["x", "y"])
    p = Point(3, 4)
    print(p.x, p.y)
    Output
    3 4

    04deque for fast ends

    main.py
    from collections import deque
    q = deque([1, 2, 3])
    q.appendleft(0)
    q.append(4)
    print(list(q))
    Output
    [0, 1, 2, 3, 4]

    05Most common elements

    main.py
    from collections import Counter
    print(Counter("mississippi").most_common(2))
    Output
    [('i', 4), ('s', 4)]