Sometimes, we may need get some random pairs or elements from a python dictionary. In this tutorial, we will use an example to show you how to do.
Get random N pairs from a dictionary in python
First, we will create a python dictionary with some values.
import random d = {'lily': 20, 'city': 'beijin', 'name':'lily',"file":"1.wav","score": 30}
This dictionary d contains 5 pairs.
We will get 4 pairs randomly in this example, which means N = 4.
random_num = 4 m = [(k, d[k]) for k in random.sample(list(d.keys()), random_num)] print(m)
Run this code, we will see:
[('score', 30), ('lily', 20), ('name', 'lily'), ('city', 'beijin')]
In order to understand random.sample(), you can see:
Understand Python random.sample(): Return a Random Sample Sequence