python - 自定义数据结构:具有累积值的字典字典
问题描述
语境
我正在编写一个 python 脚本,该脚本操纵 Google 提供的相对于 Play 商店中已安装应用程序的统计信息。
特别是,我正在为每个应用程序记录每个国家/地区每月的安装量。鉴于 Google 通过每个国家/地区每天一行的 csv 文件提供这些信息,我必须构建一个自定义数据结构来存储值,同时解析所有行的所有行。
至今
我想出了一本字典。第一级字典的键是月份(datetime
对象)。值是字典,其中键是国家,值是相应国家/地区相应月份的累计安装量。
这给了我一本结构的字典{Month : {Country : amount_of_installs} }
这允许我构建以下函数来逐步填充我的字典:
def addNewValue(dictionary, month, country, valueToAdd):
if month in dictionary:
if country in dictionary[month]:
dictionary[month][country] += valueToAdd
else:
dictionary[month][country] = valueToAdd
else:
dictionary[month] = {country: valueToAdd}
问题
虽然这是一个可行的解决方案,但感觉就像一个严重的非最佳黑客。因此,为了教育起见,我想知道对于这样的任务是否还有另一种更好的解决方案。也许是另一个我不知道的更优化的数据结构,一个现有的类已经设法以更好的方式做到这一点。
就是这样,谢谢你的建议!
解决方案
您可以使用嵌套的defaultdict
:
from collections import defaultdict as dd
dictionary = dd(lambda: dd(int))
如果您将所述数据结构传递给您的函数,则该函数可以简单地是:
def addNewValue(dictionary, month, country, valueToAdd):
dictionary[month][country] += valueToAdd
推荐阅读
- c# - 错误 - 找不到 C:\Program Files (x86)\Common Files\microsoft shared\TextTemplating\14.0\texttransform.exe 工具
- sql - SQL Server unpivot 与多列
- android - 通知两个同名的 pojo 字段数据绑定
- flutter - Flutter 设备管理员权限
- c++ - 在 C++ 中使用向量创建一个新的反向列表(自己的类)
- c++ - 如何访问 QMediaPlayer 的元数据?
- swift - Core Data 通用获取请求
- android - Android:调用完成()后应用程序仍在运行
- swift - Swift 4 Sqlite 数据库没有这样的表错误
- azure - 在 Azure 日志中的哪里可以找到我的自定义 HTTP 标头?