How to remove random elements from a dictionary in Python?
I need to remove the specified number of elements from the dictionary, so I tried to use dict.popitemwhich, as I thought, was random, but it looks like it is not.
As the docs say:
Delete and return arbitrary (key, value) from the dictionary.
For my problem, suppose I have a dictionary like (example):
>>> d = dict(zip((string.ascii_lowercase), range(1, 10)))
>>> d
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8}
Now I need to remove some elements from it (the counter is specified by the user).
So I wrote this:
>>> for _ in range(4):
... d.popitem()
...
('a', 1)
('c', 3)
('b', 2)
('e', 5)
But the problem with this code is that every time the script is executed, it popitem()displays exactly the same elements. You can test it, I already tried it several times.
So my question is: