Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to randomly choose multiple keys and its value in a dictionary python

Tags:

I have a dictionary like this:

user_dict = {             user1: [(video1, 10),(video2,20),(video3,1)]             user2: [(video1, 4),(video2,8),(video6,45)]             ...             user100: [(video1, 46),(video2,34),(video6,4)]                              }   (video1,10) means (videoid, number of request) 

Now I want to randomly choose 10 users and do some calculation like

 1. calculate number of videoid for each user.   2. sum up the number of requests for these 10 random users, etc 

then I need to increase the random number to 20, 30, 40 respectively

But "random.choice" can only choose one value at a time, right? how to choose multiple keys and the list following each key?

like image 454
manxing Avatar asked Apr 12 '12 14:04

manxing


People also ask

How do I randomly select a dictionary key in Python?

To get a random value from a dictionary in Python, you can use the random module choice() function, list() function and dictionary values() function. If you want to get a random key from a dictionary, you can use the dictionary keys() function instead.

How do you randomize a dictionary in Python?

Python dictionary is not iterable. Hence it doesn't have index to be randomized. Instead collection of its keys is iterable and can be randomized by shuffle() function in random module.

How create dictionary with multiple values for a key in Python?

In python, if we want a dictionary in which one key has multiple values, then we need to associate an object with each key as value. This value object should be capable of having various values inside it. We can either use a tuple or a list as a value in the dictionary to associate multiple values with a key.

Can you have multiple keys for one value Python?

Answer. No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored.


1 Answers

That's what random.sample() is for:

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

This can be used to choose the keys. The values can subsequently be retrieved by normal dictionary lookup:

>>> d = dict.fromkeys(range(100)) >>> keys = random.sample(list(d), 10) >>> keys [52, 3, 10, 92, 86, 42, 99, 73, 56, 23] >>> values = [d[k] for k in keys] 

Alternatively, you can directly sample from d.items().

like image 164
Sven Marnach Avatar answered Sep 28 '22 03:09

Sven Marnach