Python - 按值合并键
给定字典,合并键以映射到公共值。
例子:
Input : test_dict = {1:6, 8:1, 9:3, 10:3, 12:6, 4:9, 2:3}
Output : {‘1-12’: 6, ‘2-9-10’: 3, ‘4’: 9, ‘8’: 1}
Explanation : All the similar valued keys merged.
Input : test_dict = {1:6, 8:1, 9:3, 4:9, 2:3}
Output : {‘1’: 6, ‘2-9’: 3, ‘4’: 9, ‘8’: 1}
Explanation : All the similar valued keys merged.
方法:使用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))
输出:
The original dictionary is : {1: 6, 8: 1, 9: 3, 10: 3, 12: 6, 4: 9, 2: 3}
The required result : {‘1-12’: 6, ‘2-9-10’: 3, ‘4’: 9, ‘8’: 1}