最近因为工作需要,自己创造了或在网上大佬给的代码示例基础上整合了一些功能。
1、字典的反转
目的:将相同值的键合并,形成新的键值对
代码示例:
def dict_flip(dict_source): """ 反转字典 parameter: dict_source : 字典来源 return: dict_flipped: 反转后的字典 """ dict_flipped = {} for key, value in dict_source.items(): if value not in dict_flipped: dict_flipped[value] = [key] else: dict_flipped[value].append(key) return dict_flipped
思路:创造一个新字典,然后循环遍历键值对,如果值未在新字典的键上则添加新列表,若有则在列表基础上继续添加。
a = {'A': 'b', 'B': 18, 'C15': 'who are you', 'D':18} print(dict_flip(a))
输出结果:
{'b': ['A'], 18: ['B', 'D'], 'who are you': ['C15']}
2、字典的合并
目的:将两个字典合并,具有相同键的值合并,生成新字典。
代码示例:
def merge_dict(dict_a, dict_b): """ parameter: dict_a : 传入的字典a dict_b: 传入的字典b return: return_dict: 合并后的字典 将两个字典合并,相同键的值若为字符串和数字则相加,列表则合并 """ return_dict = {} if not dict_a: if not dict_b: return {} else: return dict_b else: if not dict_b: return dict_a else: dict_same = dict_a.keys() & dict_b.keys() a_different = dict_a.keys() - dict_b.keys() b_different = dict_b.keys() - dict_a.keys() for i in dict_same: return_dict[i] = dict_a[i] + dict_b[i] for i in a_different: return_dict[i] = dict_a[i] for i in b_different: return_dict[i] = dict_b[i] return return_dict
思路:传入要合并的字典A和B,判断是否为空,都不为空则进行相同键的值合并。
a = {'A': 'b', 'B': 18, 'C15': ['who are you'], 'D': [18]} b = {'A': 'b', 'B': 18, 'C15': ['who are you'], 'D': [18]} print(merge_dict(a, b))
输出:{'A': 'bb', 'C15': ['who are you', 'who are you'], 'D': [18, 18], 'B': 36}