Removing items randomly from a dictionary

2024/6/30 15:53:39

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?
Answer

Is this what you're talking about?

import random
for i in range(4):some_dict.pop( random.choice(some_dict.keys()) )   
https://en.xdnf.cn/q/73375.html

Related Q&A

Requests-html results in OSError: [Errno 8] Exec format error when calling html.render()

I am using requests-html and trying the render function, with little success. When I run this script using python3.8 #!/usr/bin/python3 from requests_html import HTML file = "scrape/temp_file2.ht…

Python setuptools: packaging the root directory (no subdirectory per package wanted)

I need to write a package into a repository, but it is a small quick package, so I dont see the need to put files into a subdirectory. I simply want: import mypkg.module1with directory structure root_f…

ImportError when trying to import python module in SublimeText2

Im new to SublimeText2. So far I have found it excellent, but I just came across a problem I did not manage to solve. Im trying to import a Python module, mechanize, into my script. However, whenever a…

sendfile() failed (32: Broken pipe) while sending request to upstream nginx 502

I am running Django, uwsgi, ngix server. My server works fine for GET, POST requests of smaller size. But when POSTing requests of large size, nginx returns 502: nginx error.log is: 2016/03/01 13:52:1…

Python introspection - how to check current module / line of call from within function

I have a function:# utils.py def hello(name=World):# Detect where Im being called from.print(Hi, %s. You called this from %s at line # %d. % (name, mod, lineno))# ``mod`` and ``lineno`` on previous lin…

Flask blueprints with gevent working outside of application context

I am trying to send emails asynchronously with in Flask with gevent via flask-mail. I am getting "working outside of application context". I am aware of with app.app_context() but I cannot ge…

how to optimally count elements in a python list

This is almost the same question than here, except that I am asking about the most efficient solution for a sorted result.I have a list (about 10 integers randomly between 0 and 12), for example:the_li…

How to install and run virtualenv on MacOS correctly

Hi Im a beginner of python, I dont remember when and how I installed python3.8 on my Macbook air, only knew the installed path: % which python /usr/bin/python % which python3 /usr/local/bin/python3The …

comparing a string 1-d numpy array elementwise

I have two 1-d arrays (a and b) containing strings, which I want to compare element wise to get output c like shown below. I tried converting it to set and comparing, however that does not give the cor…

Can Atom work with Python virtualenvwrapper

I want to start a Flask app. I installed virtualenvwrapper to manage the packages but I cant let Atom know that the current project should use the virtualenvs python binary.from flask import Flask, ren…