随机选择2个字典:具有相同的值



从字典中随机选择2个值为[0]== 'C'的字典。

d = {"1": ('B', [3, 4, 8]), "2": ('C', [2, 6, 8]), "3": ('C', [9, 10, 11, 13]), "4": ("E", [14, 15, 16, 17]), "5": ("C", [20])}
for key, val in d.items():
if val[0] == 'B':
b = val[0] == 'C'
res = key, val = random.choice(list(d.items()))
print(res)
e = {"2": ('C', [2, 6, 8]), "3": ('C', [9, 10, 11, 13])}
e = {"2, 3": ('C', [2, 6, 8] , [9, 10, 11, 13])}

如果您希望所选的两个元组彼此不同,请尝试以下操作:

>>> dict(random.sample([(k, v) for k, v in d.items() if v[0] == "C"], 2))
{'5': ('C', [20]), '3': ('C', [9, 10, 11, 13])}

相关内容

  • 没有找到相关文章

最新更新