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?
CodePudding user response:
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.
CodePudding user response:
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.