How do I remove random items from a dictionary in Python?
I have to remove a specified number of items from a dictionary and so I tried to use dict.popitem
which I thought was random, but it is seems it is not.
As the docs say:
Remove and return an arbitrary (key,value) pair from the dictionary.
For my problem, suppose I have a dictionary like (an 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 items from it (the count is specified by the user).
So I wrote this:
>>> for _ in range(4): # assume 4 items have to removed
... d.popitem()
...
('a', 1)
('c', 3)
('b', 2)
('e', 5)
But the problem with this code is, every time the script is run, popitem()
pops exactly the same items. You are free to test this, I have already tried it multiple times.
So my question is:
- Why isn't
popitem()
working the way it should? Is removing arbitrary items not random? - How do I remove random items from a dictionary?