How to get random selected values from dictionary

Viewed 60

I am having a directory that contains an N number of key and values and I want to iterate only 4 random and unique keys and values and then need to check the highest and lowest key and values among 4 entries then find the subtraction.

let consider:

    main_dict = {"a":144,"c":55,"d":33,"e":65,"f":44,"s":344,"r":90,"t":33}
   
    random_key_and_values = 4

the new dictionary will be

    new_dict = {"c":55,"f":44,"r":90,"d":33}

with the new dictionary, I need the subtraction of the highest and lowest values of new_dict values.

    output  = 57
2 Answers

@tino's answer may work, but it can be done without third-party libraries, just with builtins:

import random

main_dict = {"a" : 144, "c" : 55, "d" : 33, "e" : 65, "f" : 44, "s" : 344, "r" : 90, "t" : 33}
rand_choice_len = 4
new_dict = dict(random.choices(list(main_dict.items()), k=rand_choice_len))
output = max(new_dict.values()) - min(new_dict.values())
print(new_dict, "difference of highest and lowest is:", output)

References:
random.choices
max
min dict

The code below should be what you are looking for. A couple loops and np.random.choice

import numpy as np

main_dict = {"a":144,"c":55,"d":33,"e":65,"f":44,"s":344,"r":90,"t":33}
   
random_key_and_values = 4

new_dict = { key : main_dict[key] for key in np.random.choice(np.array(list(main_dict.keys())),random_key_and_values)}

diff = np.array(list(new_dict.values())).max() - np.array(list(new_dict.values())).min()

print(diff)
Related