Python字典列表去重
-
最近在写代码时老是遇到 字典列表 的去重,想当然的就用上了 set(),哈哈哈哈哈直接上代码
list_a = [{"name": "Tom", "age": 18}, {"name": "Jerry", "age": 18}, {"name": "Tom", "age": 18}] unique_list = list(list_a) print(unique_list)
-
结果
TypeError: unhashable type: 'dict'
set / dict 使用 hash 值进行索引,也即其要求欲存储的元素有可哈希的要求,而列表中的元素为 dict
Python debug——TypeError: unhashable type(list/set/dict) -
那就暴力去重吧
list_a = [{"name": "Tom", "age": 18}, {"name": "Jerry", "age": 18}, {"name": "Tom", "age": 18}] unique_list = [] for item in sorted(list_a, key=lambda x: x["name"]): if item not in unique_list: unique_list.append(item) print(unique_list)
刚好学习一下时间复杂度 & 空间复杂度,处理列表前给排序上,平庸写法,结果不会错
[{'name': 'Jerry', 'age': 18}, {'name': 'Tom', 'age': 18}]
我当然不可能这么平庸,继续冲浪新方法,列表中相同的字典去重
def list_dict_duplicate_removal(data_list): """ 列表中字典去重函数 :param data_list: 嵌套字典的列表 如:[{"a":1},{"b":2}] :return: """ run_function = lambda x, y: x if y in x else x + [y] from functools import reduce # reduce为python内置函数 return reduce(run_function, [[], ] + data_list)
-
简化成一行代码
list_a = [{"name": "Tom", "age": 18}, {"name": "Jerry", "age": 18}, {"name": "Tom", "age": 18}] unique_list = functools.reduce(lambda x, y: y in x and x or x + [y], list_a, [])
结果没问题,处理得很完美,👍
[{'name': 'Tom', 'age': 18}, {'name': 'Jerry', 'age': 18}]
不知道大伙看代码会不会骂我,反正我同事已经骂了,装神弄鬼,哈哈哈哈哈。不过我觉得多用些不一样的东西是好的,熟能生巧,日复一日cv真的累了。回到代码,其实就是functools.reduce() 再加上 and or 代替 三元表达式 ,🔚