[英]Finding a list of keys containing equal values in a dictionary
我想在字典中找到包含等於其他元素的值的所有鍵的列表(列表)。
例如:
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
?
您可以使用翻轉字典從字典中查找重復值。
您可以通過迭代原始字典並將每個值作為鍵添加到翻轉字典中來創建它,並且它是鍵即值。 然后,如果該值再次出現在原始字典中,則將其鍵添加為翻轉字典中的另一個值。
然后你可以查看翻轉字典中的每個鍵,檢查它是否有超過 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)
。
迭代 dict 項目,並為每個值將鍵添加到正確的列表中。
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)
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)
它將為您提供所有具有相同鍵的列表
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 所建議的那樣。
對我來說,第一個變體更清晰(但不那么簡潔)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.