简体   繁体   English

在 Python 的特定条件下随机检索字典中的值

[英]Retrieving randomically values in a dictionary with specific conditions in Python

I want to extract one key out of my dictionary where the value is >= 0.05.我想从我的字典中提取一个值 >= 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.我希望startActivity是这些键的随机名称,比如我第一次运行代码时是startActivity = Bed_to_Toilet ,第二次是startActivity = Guest_Bathroom等等。 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.它工作得很好,我只需要一种添加条件的方法。

1st, get a list of reference keys that match your criteria: 1,获取符合您条件的参考键列表:

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

Then you can random.choice from that list:然后你可以从那个列表中random.choice选择:

mykey = random.choice(candidate_list)

At which point, if wanted, you can go back and access the value chosen:此时,如果需要,您可以返回 go 并访问所选值:

myval = startActModel[mykey]

If you want to keep your API unchanged.如果你想保持你的 API 不变。 You can pass to findFirstActivity() a filtered version of your dict.您可以向findFirstActivity()传递您的字典的过滤版本。 Thanks to a dict comprehension.感谢听写理解。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM