Python – 对字典中的相似键进行分组
有时在处理字典数据时,我们可能会遇到需要根据键的子串进行分组并重新组合在相似键上分组的数据的问题。这可以应用于数据预处理。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是我们执行此任务的粗暴方式。在此,我们使用条件语句检查元素并根据子字符串的存在插入键。
# Python3 code to demonstrate working of
# Group Similar keys in dictionary
# Using loop
# initializing Dictionary
test_dict = {'gfg1' : 1, 'is1' : 2, 'best1' : 3,
'gfg2' : 9, 'is2' : 8, 'best2' : 7,
'gfg3' : 10, 'is3' : 5, 'best3' : 6}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Group Similar keys in dictionary
# Using loop
res = []
res1, res2, res3 = {}, {}, {}
for key, value in test_dict.items():
if 'gfg' in key:
res1[key] = value
elif 'is' in key:
res2[key] = value
elif 'best' in key:
res3[key] = value
res.append(res1)
res.append(res2)
res.append(res3)
# printing result
print("The grouped similar keys are : " + str(res))
The original dictionary is : {‘best2’: 7, ‘best3’: 6, ‘is2’: 8, ‘is3’: 5, ‘best1’: 3, ‘gfg1’: 1, ‘gfg3’: 10, ‘is1’: 2, ‘gfg2’: 9}
The grouped similar keys are : [{‘gfg3’: 10, ‘gfg2’: 9, ‘gfg1’: 1}, {‘is2’: 8, ‘is3’: 5, ‘is1’: 2}, {‘best3’: 6, ‘best1’: 3, ‘best2’: 7}]
方法#2:使用字典理解
这是可以执行此任务的另一种方式。在此,我们使用字典理解将子字符串分组为键。
# Python3 code to demonstrate working of
# Group Similar keys in dictionary
# Using dictionary comprehension
# initializing Dictionary
test_dict = {'gfg1' : 1, 'is1' : 2, 'best1' : 3,
'gfg2' : 9, 'is2' : 8, 'best2' : 7,
'gfg3' : 10, 'is3' : 5, 'best3' : 6}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Group Similar keys in dictionary
# Using dictionary
res = []
res1 = {key : val for key, val in test_dict.items() if 'gfg' in key}
res2 = {key : val for key, val in test_dict.items() if 'is' in key}
res3 = {key : val for key, val in test_dict.items() if 'best' in key}
res.append(res1)
res.append(res2)
res.append(res3)
# printing result
print("The grouped similar keys are : " + str(res))
The original dictionary is : {‘best2’: 7, ‘best3’: 6, ‘is2’: 8, ‘is3’: 5, ‘best1’: 3, ‘gfg1’: 1, ‘gfg3’: 10, ‘is1’: 2, ‘gfg2’: 9}
The grouped similar keys are : [{‘gfg3’: 10, ‘gfg2’: 9, ‘gfg1’: 1}, {‘is2’: 8, ‘is3’: 5, ‘is1’: 2}, {‘best3’: 6, ‘best1’: 3, ‘best2’: 7}]