博客
关于我
Python 字典键映射多个值,字典值为列表,defaultdict
阅读量:256 次
发布时间:2019-03-01

本文共 689 字,大约阅读时间需要 2 分钟。

背景

在处理大量数据时,涉及到元组或列表的记录归纳统计时,需要将所有列表转换为字典以便统计。以下是一个示例:

l1 = ['张三', '语文', 50]l2 = ['李四', '语文', 60]l3 = ['张三', '数学', 70]l4 = ['李四', '数学', 60]

期望结果为:

{    '张三': [50, 70],    '李四': [60, 60]}

代码

from collections import defaultdictl1 = ['张三', '语文', 50]l2 = ['李四', '语文', 60]l3 = ['张三', '数学', 70]l4 = ['李四', '数学', 60]result = defaultdict(list)for record in (l1, l2, l3, l4):    name = record[0]    score = record[2]    result[name].append(score)print(result)

分析

defaultdict的作用是,当字典中的键不存在时,返回默认值而不是KeyErrordefaultdict接受一个工厂函数作为参数,用于在键不存在时创建默认值。例如:

  • defaultdict(list):当键不存在时,返回一个空列表。
  • defaultdict(set):当键不存在时,返回一个空集合。
  • defaultdict(str):当键不存在时,返回一个空字符串。

优点

  • 不再需要检查字典键是否存在。
  • 代码简洁,易于维护。
  • 适合批量处理数据。

参考文章

你可能感兴趣的文章
python 中文乱码
查看>>
Python 中生成器与普通函数的区别
查看>>
Python 中的 *tuple 和 **dict 是什么意思?
查看>>
Python 中的 filter() 函数:筛选可迭代对象元素
查看>>
Python 中的 Pillow 不允许我打开图像(“超出限制“)
查看>>
Python 中的 threading 模块和 multiprocessing 模块有何区别?
查看>>
Python 中的 threading 模块和 multiprocessing 模块有何区别?
查看>>
Python 中的 Turtle 库详解
查看>>
Python 中的 __slots__ 属性有什么作用?
查看>>
Python 中的... 三点、箭头(->)、/ 分别的作用
查看>>
python读取json数据的id_python处理JSON数据
查看>>
Python 中的Duck Typing
查看>>
Python 中的for in 遍历生成字典、添加判断条件if
查看>>
Python 中的Lock与RLock
查看>>
Python 中的range(),arange()函数
查看>>
Python 中的内存管理机制
查看>>
Python 中的函数包装器:模型运行时和调试
查看>>
Python 中的列表理解和 lambda
查看>>
Python 中的多层for in嵌套循环使用
查看>>
Python 中的多线程(01/4)
查看>>