python - 在字典中查找包含相等值的键列表
问题描述
我想在包含等于其他元素的值的字典中找到所有键的列表(列表)。
例如:
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)
时间复杂度。
推荐阅读
- vba - 错误转到:获取错误消息-2147024809
- android - 如何在从服务器加载 100 多个对象并将其设置为适配器时避免 ANR;在安卓中
- sql - 使用更新触发器连接两列
- c++ - 如何在 QT 中不断读取 UDP 数据包?
- api - 使用 Google 距离矩阵 API 时的不同响应
- excel - Excel:使用两个输入从两个表中查找一个值
- php - 使用 AJAX 加载更多产品 WooCommerce
- python - win32file.WaitForMultipleObjects 如何等待所有对象
- javascript - 从txt文件到网页的数据
- python - 为什么这段代码在 python 中没有着色?