Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...