Extract items from a dictionary

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):          # assume 4 items have to removed
...     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:

  • popitem() , ? ?
  • ?
+3
6

, ?

import random
for i in range(4):
    some_dict.pop( random.choice(some_dict.keys()) )   
+15

"" , , . , .

random. :

import random
for key in random.sample(d.keys(), 4):
   del d[key]
+8

popitem() , .

import random
key = random.choice(d.keys())
val = d[key]
del d[key]
+7
  • popitem() , ? ?

- , . , , , .

  • ?

, , :

import random
dict.pop(random.choice(dict.keys())
+4

random.sample dict.keys random.choice

for key in random.sample(d.keys(), n):
    del d[key] # or d.pop(key)
+3
d = {'spam': 0,'url': 'http://www.python.org',  'title': 'Python Web Site'}
d.popitem()
print d

{ }, URL-

d = {'spam': 0,'arl': 'http://www.python.org',  'title': 'Python Web Site'}
d.popitem()
print d

: 'u' url 'a'

, ASCII, \

+1

Source: https://habr.com/ru/post/1788012/


All Articles