![](/img/trans.png)
[英]Find the key of maximum values of maximum key in a dictionary in case of duplicates of values
[英]Find dynamic dictionary key values duplicates
我正在创建一个这样的动态字典:
a_list = ("Item1", "Item2", "Item3")
b_list = ("Item4", "Item5")
c_list = ("Item6", "Item7", "Item8", "Item9")
dct = {}
for x in range(100):
dct['key_%s' % x] = []
a = random.choice(a_list)
dct['key_%s' % x].append(a)
b = random.choice(b_list)
dct['key_%s' % x].append(b)
c = random.choice(c_list)
dct['key_%s' % x].append(c)
我在每个新 key_ 中填充了一个项目列表a、b、c ,这些项目从a_list、b_list、c_list中获取随机值
现在我只想为dct字典中的每个键设置唯一的 a、b、c值,所以在完成附加后,我想将最后一个字典项与之前的所有项进行比较,如果找到重复项,则可能会删除该键对并减小x ,以便它尝试添加另一个a、b、c值组合。
这也是我尝试过的:
dct_values = list(dct.values())
if len(dct_values) > 1:
last_item = list(dct.values())[-1]
for allists in list(dct.values())[0:-1]:
if last_item == allists:
print(f"Duplicate found on {x} >> {last_item}")
dct.popitem()
x = x - 1
这将给我唯一的值,但 key_# 不是连续的,代码看起来很难看
预期结果是一个字典,其中包含来自 a、b、c _list 的唯一列表键值
IIUC,您可以使用生成随机唯一项目的生成器:
import random
a_list = ("Item1", "Item2", "Item3")
b_list = ("Item4", "Item5")
c_list = ("Item6", "Item7", "Item8", "Item9")
def get_items(*lists):
duplicates = set()
while True:
items = tuple(random.choice(l) for l in lists)
if items not in duplicates:
duplicates.add(items)
yield items
dct = {
f"key_{i}": items
for i, items in zip(range(10), get_items(a_list, b_list, c_list))
}
print(dct)
打印(例如):
{
"key_0": ("Item3", "Item4", "Item9"),
"key_1": ("Item2", "Item5", "Item8"),
"key_2": ("Item2", "Item4", "Item6"),
"key_3": ("Item1", "Item4", "Item6"),
"key_4": ("Item1", "Item5", "Item7"),
"key_5": ("Item2", "Item5", "Item6"),
"key_6": ("Item1", "Item5", "Item6"),
"key_7": ("Item3", "Item4", "Item7"),
"key_8": ("Item1", "Item5", "Item8"),
"key_9": ("Item3", "Item5", "Item8"),
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.