这是一个简单的解决方案。
# Original dictionary
d = {'A': 1, 'z': 1, 'Y': 1, 'a': 3, 'y': 1}
# Split the dictionary into 2 parts
lower_case_keys = dict((key, value) for key, value in d.items() if key.islower())
Output: {'z': 1, 'a': 3, 'y': 1}
upper_case_keys = dict((key, value) for key, value in d.items() if key.isupper())
Output: {'A': 1, 'Y': 1}
# Convert lower_case_keys to upper case for uniformity
lower_case_keys_to_upper_case = dict((key.upper(), value) for key, value in d.items())
output: {'A': 3, 'Z': 1, 'Y': 1}
from collections import Counter
final_dict = dict(Counter(lower_case_keys_to_upper_case) + Counter(upper_case_keys))
Output: {'A': 4, 'Z': 1, 'Y': 2}
所有这些都可以组合成一个函数。
from collections import Counter
def get_case_insensitive_sum(d):
lower_case_keys = dict((key, value) for key, value in d.items() if key.islower())
upper_case_keys = dict((key, value) for key, value in d.items() if key.isupper())
lower_case_keys_to_upper_case = dict((key.upper(), value) for key, value in d.items())
final_dict = dict(Counter(lower_case_keys_to_upper_case) + Counter(upper_case_keys))
print(final_dict)
d = {'A': 1, 'z': 1, 'Y': 1, 'a': 3, 'y': 1}
get_case_insensitive_sum(d)
Output: {'A': 4, 'Z': 1, 'Y': 2}