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

Question:

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?

Asked By: manxing

||

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().

Answered By: Sven Marnach

Simply

import random
mydict = {"a":"its a", "b":"its b"}
random.sample(mydict.items(), 1)

# [('b', 'its b')]
# or
# [('a', 'its a')]

Answered By: Deepak Sharma

I have work on this problem,

import random

def random_a_dict_and_sample_it( a_dictionary , a_number ): 
    _ = {}
    for k1 in random.sample( list( a_dictionary.keys() ) , a_number ):
        _[ k1 ] = a_dictionary[ k1 ]
    return _

In your case:

user_dict = random_a_dict_and_sample_it( user_dict , 2 )
Answered By: Gromph

If you wanted to return a dictionary, you could use a dictionary comprehension instead of the list comprehension in Sven Marnach’s answer like so:

d = dict.fromkeys(range(100))
keys = random.sample(d.keys(), 10)
sample_d = {k: d[k] for k in keys}
Answered By: jss367
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.