我想在字典中找到包含所有等于其他元素的值的所有键的列表(列表)。
例如:
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
?
答案 0 :(得分:3)
您可以使用翻转字典从字典中找到重复的值。
您可以通过迭代原始词典并将每个值作为键添加到翻转的词典中来创建它,并且将键值作为它的值。然后,如果该值再次出现在原始字典中,则将其键添加为翻转字典中的另一个值。
然后,您只需遍历翻转字典中的每个键,检查它是否具有大于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)
的时间复杂度。
答案 1 :(得分:1)
遍历字典项,并为每个值将键添加到正确的列表中。
from collections import defaultdict
res = defaultdict(list)
for k, v in dict_with_dups.items():
res[v].append(k)
for v in res.values():
if len(v) > 1:
print(v)
答案 2 :(得分:0)
dict_with_dups = {
"a": 1,
"b": 1,
"c": 1,
"d": 2,
"e": 3,
"f": 3,
"g": 4,
}
result = {}
for val in dict_with_dups:
if dict_with_dups[val] in result:
result[dict_with_dups[val]].append(val)
else:
result[dict_with_dups[val]] = [val]
for key, value in result.items():
if len(value)>1:
print(value)
它将为您提供所有具有相同键的列表
答案 3 :(得分:0)
dict_with_dups = {
"a": 1,
"b": 1,
"c": 1,
"d": 2,
"e": 3,
"f": 3,
"g": 4,
}
result = list(filter(lambda z: len(z)>1,
(list(map(lambda y: y[0],
filter(lambda x: x[1]==v, dict_with_dups.items())))
for v in set(dict_with_dups.values()))))
或
result = [z for z in ([x[0] for x in dict_with_dups.items() if x[1]==v]
for v in set(dict_with_dups.values()))
if len(z)>1]
如@wjandrea所建议。
对我来说,第一个变体更清晰(但不太简洁)。