Home > Blockchain >  Retrieving randomically values in a dictionary with specific conditions in Python
Retrieving randomically values in a dictionary with specific conditions in Python

Time:11-08

I want to extract one key out of my dictionary where the value is >= 0.05. My dictionary looks like this

{'Bed_to_Toilet': 0.5645161290322581, 
'Sleep': 0.016129032258064516, 
'Morning_Meds': 0.03225806451612903, 
'Watch_TV': 0.0, 
'Kitchen_Activity': 0.04838709677419355, 
'Chores': 0.0, 
'Leave_Home': 0.03225806451612903, 
'Read': 0.0, 
'Guest_Bathroom': 0.08064516129032258, 
'Master_Bathroom': 0.22580645161290322}

and I want startActivity to be a random name from these keys, like the first time I run my code is startActivity = Bed_to_Toilet, the second time is startActivity = Guest_Bathroom and so on. How can I do it?

I tried doing this

def findFirstActivity(self, startActModel):
   startActivity, freq = random.choice(list(startActModel.items()))
   return startActivity

and it works pretty well, I just need a way to add for a condition.

CodePudding user response:

1st, get a list of reference keys that match your criteria:

candidate_list = [k for k,v in startActModel.items() if v >= 0.05]

Then you can random.choice from that list:

mykey = random.choice(candidate_list)

At which point, if wanted, you can go back and access the value chosen:

myval = startActModel[mykey]

CodePudding user response:

If you want to keep your API unchanged. You can pass to findFirstActivity() a filtered version of your dict. Thanks to a dict comprehension.

filtered_startActModel = {k:v for k, v in d.items() if v >= 0.05}
  • Related