2

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 
4
  • Can you share what have you tried? Commented Apr 25, 2021 at 9:38
  • I will quickly share Commented Apr 25, 2021 at 9:40
  • Something like random.choices is what you need Commented Apr 25, 2021 at 9:44
  • Please accept an answer using the grey checkmark on the left of it. Commented Apr 25, 2021 at 19:24

2 Answers 2

2

@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

Sign up to request clarification or add additional context in comments.

2 Comments

You can use dict(...) instead of {k: v for k, v in ...} - the dict constructor accepts an iterable of pairs.
@kaya3 thanks, weird I didn't encounter that when searching for "python dict from items" …
0

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) 

2 Comments

Using numpy can be handy sometimes, but sometimes, it can be an overkill ...
why is that? Never really understood this "overkill" idea. Numpy is rather standard in every python distribution, why not using it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.