📜  Python - 按值合并键

📅  最后修改于: 2022-05-13 01:55:29.074000             🧑  作者: Mango

Python - 按值合并键

给定字典,合并键以映射到公共值。

例子:

方法:使用defaultdict() + 循环

此任务分两步执行,首先,将所有值分组并存储键,然后在第二步中将合并的键映射到公共值。

Python3
# Python3 code to demonstrate working of
# Merge keys by values
# Using defaultdict() + loop
from collections import defaultdict
 
# initializing dictionary
test_dict = {1: 6, 8: 1, 9: 3, 10: 3, 12: 6, 4: 9, 2: 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# grouping values
temp = defaultdict(list)
for key, val in sorted(test_dict.items()):
    temp[val].append(key)
 
res = dict()
# merge keys
for key in temp:
    res['-'.join([str(ele) for ele in temp[key]])] = key
 
# printing result
print("The required result : " + str(res))


输出: