简体   繁体   English

从python中的字典的字典中随机选择

[英]randomly select from dictionary of a dictionary in python

I have defined dictionary of dictionary of the form: 我已经定义了字典形式的字典:

my_dict = {
    "my_key1": {"key_1": value_1, "key_2": value_2},
    "my_key2": {"key_1": value_1, "key_2": value_2, "key_3": value_3},
    "my_key3": {"key_1": value_1, "key_2": value_2, "key_3": value_3, , "key_4": value_4},
    "my_key4": {"key_1": value_1, "key_2": value_2}
}

I want to randomly select one "value" for each my_key. 我想为每个my_key 随机选择一个“值”。 I tried below which didn't work: 我尝试了以下无效的方法:

for key in my_dict:
    # randomly select from the sub-dictionary
        rand = random.sample(list(param[key]), 1)
    # get value at that randomVal
        net[key] = param[key][rand]

Is there any other way to randomly select the values for each key. 还有其他方法可以随机选择每个键的值。 Thanks in advance! 提前致谢!

IIUC, you can use list comprehension and random.choice IIUC,您可以使用list comprehensionrandom.choice

>>> r = [random.choice(list(v.values())) for k,v in my_dict.items()]
['value_2', 'value_2', 'value_3', 'value_4'] # example

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

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