首页 > 编程语言 > 详细

python-找出字典dic中重复值

时间:2020-06-19 19:00:36      阅读:151      评论:0      收藏:0      [点我收藏+]
# 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/

python-找出字典dic中重复值

原文:https://www.cnblogs.com/muyuequzhi/p/13164337.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!