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

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}

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 )

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

Tags:

Python