python-找出字典dic中重复值
# 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))
Output:
initial_dictionary {'a': 1, 'c': 3, 'd': 2, 'b': 2}
final_dictionary {1: ['a'], 2: ['d', 'b'], 3: ['c']}
如果只想要重复的值可参考以下代码
# 因为在遍历字典时不能更改字典内容,所以for key in list(flipped.keys())
for key in list(flipped.keys()):
if len(flipped[key]) < 2:
del flipped[key]
print(flipped)
Output:
{2: ['b', 'd']}
参考:https://www.geeksforgeeks.org/python-find-keys-with-duplicate-values-in-dictionary/