Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing items randomly from a dictionary

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?
like image 262
user225312 Avatar asked Jan 26 '11 19:01

user225312


People also ask

Can you remove items from a dictionary?

Because key-value pairs in dictionaries are objects, you can delete them using the “del” keyword. The “del” keyword is used to delete a key that does exist.

How do you randomly pick a dictionary?

Check out random. sample() which will select and return a random element from an list. You can get a list of dictionary keys with dict. keys() and a list of dictionary values with dict.

How do you delete something from the dictionary while iterating?

First, you need to convert the dictionary keys to a list using the list(dict. keys()) method. During each iteration, you can check if the value of a key is equal to the desired value. If it is True , you can issue the del statement to delete the key.

How do you randomly pick a dictionary in Python?

Use random. choice() to get a random entry items() on a dictionary to return an iterable of its entries. Call list(iterable) with iterable to convert this iterable to a list. Call random. choice(seq) with this list as seq to return a random entry.


2 Answers

Is this what you're talking about?

import random
for i in range(4):
    some_dict.pop( random.choice(some_dict.keys()) )   
like image 180
S.Lott Avatar answered Oct 04 '22 16:10

S.Lott


Removing an "arbitrary" element means that the function can remove whatever item it likes. That doesn't mean that it has to be especially random about it.

For real randomness you should use the random module. For example:

import random
for key in random.sample(d.keys(), 4):
   del d[key]
like image 25
sth Avatar answered Oct 04 '22 16:10

sth