首页 > 解决方案 > 在字典中查找包含相等值的键列表

问题描述

我想在包含等于其他元素的值的字典中找到所有键的列表(列表)。

例如:

dict_with_dups = {
    "a": 1,
    "b": 1,
    "c": 1,
    "d": 2,
    "e": 3,
    "f": 3,
    "g": 4,
}

keys_with_same = locate_same_keys(dict_with_dups)

for key_list in keys_with_same:
    print(f"{key_list}")

上面应该打印这个:

['a', 'b', 'c']
['e', 'f']

我如何最有效地编写函数locate_same_keys

标签: pythondictionary

解决方案


您可以使用翻转字典从字典中查找重复值。

您可以通过迭代原始字典并将每个值作为键添加到翻转字典中来创建它,并且它是键值。然后,如果该值再次出现在原始字典中,则将其键添加为翻转字典中的另一个值。

然后你可以检查翻转字典中的每个键,检查它是否有超过 1 个值,如果是,打印它:

dict_with_dups = {
    "a": 1,
    "b": 1,
    "c": 1,
    "d": 2,
    "e": 3,
    "f": 3,
    "g": 4,
}

# finding duplicate values from dictionary using flip 
flipped = {} 

# iterate over the original dictionary and check if each value is associated 
# with more than one key
for key, value in dict_with_dups.items(): 
    if value not in flipped: 
        flipped[value] = [key] 
    else: 
        flipped[value].append(key) 

# printing all values that are assosiated with more then one key
for key, value in flipped.items():
    if len(value)>1:
        print(value)

输出

['a', 'b', 'c']
['e', 'f']

关于效率,创建翻转字典需要遍历原始字典中的所有键值对,因此我们得到O(n)时间复杂度。


推荐阅读