Get random key:value pairs from dictionary in python

2024/10/5 11:26:47

I'm trying to pull out a random set of key-value pairs from a dictionary I made from a csv file. The dictionary contains information for genes, with the gene name being the dictionary key, and a list of numbers (related to gene expression etc.) being the value.

# python 2.7.5
import csv
import randomgenes_csv = csv.reader(open('genes.csv', 'rb'))genes_dict = {}
for row in genes_csv:genes_dict[row[0]] = row[1:]length = raw_input('How many genes do you want? ')for key in genes_dict:random_list = random.sample(genes_dict.items(), int(length))print random_list

The problem is, if I try to get a list of 100 genes (for example), it seems to iterate over the whole dictionary and return every possible combination of 100 genes.

Answer

If you want to get random K elements from dictionary D you simply use

import random
random.sample( D.items(), K )

and that's all you need.

From the Python's documentation:

random.sample(population, k)

Return a k length list of unique elementschosen from the population sequence. Used for random sampling withoutreplacement.

In your case

import csv
import randomgenes_csv = csv.reader(open('genes.csv', 'rb'))genes_dict = {}
for row in genes_csv:genes_dict[row[0]] = row[1:]length = raw_input('How many genes do you want? ')
random_list = random.sample( genes_dict.items(), int(length) )
print random_list

There is no need to iterate through all the keys of the dictionary

for key in genes_dict:random_list = random.sample(genes_dict.items(), int(length))print random_list

notice, that you are actualy not using the key variable inside your loop, which should warn you that something may be wrong here. Although it is not true that it " return every possible combination of 100 genes.", it simply returns N random k element genes lists (in your case 100), where N is the size of the dictionary, which is far from being "all combinations" (which is N!/(N-k)!k!)

https://en.xdnf.cn/q/70496.html

Related Q&A

UnicodeDecodeError: ascii codec cant decode byte 0xc5

UnicodeDecodeError: ascii codec cant decode byte 0xc5 in position 537: ordinal not in range(128), referer: ...I always get this error when I try to output my whole website with characters "č"…

wpa-handshake with python - hashing difficulties

I try to write a Python program which calculates the WPA-handshake, but I have problems with the hashes. For comparison I installed cowpatty (to see where I start beeing wrong).My PMK-generation works …

Group by column in pandas dataframe and average arrays

I have a movie dataframe with movie names, their respective genre, and vector representation (numpy arrays).ID Year Title Genre Word Vector 1 2003.0 Dinosaur Planet Documentary [-0.55423898,…

Python dynamic properties and mypy

Im trying to mask some functions as properties (through a wrapper which is not important here) and add them to the object dynamically, however, I need code completion and mypy to work.I figured out how…

Flask-login: remember me not working if login_managers session_protection is set to strong

i am using flask-login to integrate session management in my flask app. But the remember me functionality doesnt work if i set the session_protection to strong, however, it works absolutely fine if its…

Does any magic happen when I call `super(some_cls)`?

While investigating this question, I came across this strange behavior of single-argument super:Calling super(some_class).__init__() works inside of a method of some_class (or a subclass thereof), but …

How to get unpickling to work with iPython?

Im trying to load pickled objects in iPython.The error Im getting is:AttributeError: FakeModule object has no attribute WorldAnybody know how to get it to work, or at least a workaround for loading obj…

Basic questions about nested blockmodel in graph-tool

Very briefly, two-three basic questions about the minimize_nested_blockmodel_dl function in graph-tool library. Is there a way to figure out which vertex falls onto which block? In other words, to ext…

How to get multiple parameters with same name from a URL in Pylons?

So unfortunately I find myself in the situation where I need to modify an existing Pylons application to handle URLs that provide multiple parameters with the same name. Something like the following...…

Kivy: Access configuration values from any widget

Im using kivy to create a small App for computer aided learning.At the moment I have some problems with accessing config values. I get the value withself.language = self.config.get(basicsettings, langu…