Python|在字典中查找具有重复值的键
给定一个字典,任务是找到具有重复值的键。让我们讨论一些相同的方法。
方法#1:使用朴素的方法
在这个方法中,我们首先将字典值转换为具有逆映射的键,然后找到重复的键
# Python code to demonstrate
# finding duplicate values from a dictionary
# initialising dictionary
ini_dict = {'a':1, 'b':2, 'c':3, 'd':2}
# printing initial_dictionary
print("initial_dictionary", str(ini_dict))
# finding duplicate values
# from dictionary
# using a naive approach
rev_dict = {}
for key, value in ini_dict.items():
rev_dict.setdefault(value, set()).add(key)
result = [key for key, values in rev_dict.items()
if len(values) > 1]
# printing result
print("duplicate values", str(result))
输出:
initial_dictionary {'c': 3, 'b': 2, 'd': 2, 'a': 1}
duplicate values [2]
方法#2:使用翻转字典
# Python code to demonstrate
# finding duplicate values from dictionary
# initialising dictionary
ini_dict = {'a':1, 'b':2, 'c':3, 'd':2}
# printing initial_dictionary
print("initial_dictionary", str(ini_dict))
# finding duplicate values
# from dictionary using flip
flipped = {}
for key, value in ini_dict.items():
if value not in flipped:
flipped[value] = [key]
else:
flipped[value].append(key)
# printing result
print("final_dictionary", str(flipped))
输出:
initial_dictionary {'a': 1, 'c': 3, 'd': 2, 'b': 2}
final_dictionary {1: ['a'], 2: ['d', 'b'], 3: ['c']}
方法#3:使用链和集
假设您需要查找具有重复值的键。
# Python code to demonstrate
# finding duplicate values from dictionary
from itertools import chain
# initialising dictionary
ini_dict = {'a':1, 'b':2, 'c':3, 'd':2}
# printing initial_dictionary
print("initial_dictionary", str(ini_dict))
# finding duplicate values
# from dictionary using set
rev_dict = {}
for key, value in ini_dict.items():
rev_dict.setdefault(value, set()).add(key)
result = set(chain.from_iterable(
values for key, values in rev_dict.items()
if len(values) > 1))
# printing result
print("resultant key", str(result))
输出:
initial_dictionary {'b': 2, 'd': 2, 'c': 3, 'a': 1}
resultant key {'d', 'b'}
代替
result = set(chain.from_iterable(
values for key, values in rev_dict.items()
if len(values) > 1))
用这个:
result = filter(lambda x: len(x)>1, rev_dict.values())
print(list(result))