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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM