博客
关于我
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):当键不存在时,返回一个空字符串。

优点

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

参考文章

你可能感兴趣的文章
Orcale表被锁
查看>>
org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
查看>>
org.apache.poi.hssf.util.Region
查看>>
org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
查看>>
org.hibernate.HibernateException: Unable to get the default Bean Validation factory
查看>>
org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
查看>>
org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
查看>>
org.tinygroup.serviceprocessor-服务处理器
查看>>
org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
查看>>
org/hibernate/validator/internal/engine
查看>>
SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
查看>>
ORM sqlachemy学习
查看>>
Ormlite数据库
查看>>
orm总结
查看>>
os.path.join、dirname、splitext、split、makedirs、getcwd、listdir、sep等的用法
查看>>
os.system 在 Python 中不起作用
查看>>
OSCACHE介绍
查看>>
SQL--合计函数(Aggregate functions):avg,count,first,last,max,min,sum
查看>>