Search code examples
pythondictionaryordereddictionary

How do you get the first 3 elements in Python OrderedDict?


How do you get the first 3 elements in Python OrderedDict?

Also is it possible to delete data from this dictionary.

For example: How would I get the first 3 elements in Python OrderedDict and delete the rest of the elements?


Solution

  • Let's create a simple OrderedDict:

    >>> from collections import OrderedDict
    >>> od = OrderedDict(enumerate("abcdefg"))
    >>> od
    OrderedDict([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g')])
    

    To return the first three keys, values or items respectively:

    >>> list(od)[:3]
    [0, 1, 2]
    >>> list(od.values())[:3]
    ['a', 'b', 'c']
    >>> list(od.items())[:3]
    [(0, 'a'), (1, 'b'), (2, 'c')]
    

    To remove everything except the first three items:

    >>> while len(od) > 3:
    ...     od.popitem()
    ... 
    (6, 'g')
    (5, 'f')
    (4, 'e')
    (3, 'd')
    >>> od
    OrderedDict([(0, 'a'), (1, 'b'), (2, 'c')])