pythondictionary

Deleting first item in python dict using indexes


I am working with dictionaries and I would like to delete the first item of the dictionary. Is there any way to do that using indexes?


Solution

  • In Python dictionaries preserve insertion order. So if you want to delete the first inserted (key, value) pair from it you can do it this way, for example:

    >>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
    >>> del d[list(d.keys())[0]]
    >>> print(d)
    {'two': 2, 'three': 3, 'four': 4}
    

    Documentation is here.