Ghosty
Ghosty

Reputation: 37

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?

Upvotes: 2

Views: 2162

Answers (2)

Mark
Mark

Reputation: 92440

Similar to @Yevgeniy-Kosmak above but you can avoid allocating the list of keys and use a lazy iterator. This will be friendlier to memory with large dicts:

d = {
    'x': 100,
    'y': 200,
    'z': 300
}

del d[next(iter(d))]

d
# {'y': 200, 'z': 300}

Of course, this should include a caveat that if you are depending on the order of things, a dictionary may not be the best choice of data structure.

Upvotes: 3

Yevhenii Kosmak
Yevhenii Kosmak

Reputation: 3860

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.

Upvotes: 5

Related Questions