首页 > 解决方案 > 自定义数据结构:具有累积值的字典字典

问题描述

语境

我正在编写一个 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}

问题

虽然这是一个可行的解决方案,但感觉就像一个严重的非最佳黑客。因此,为了教育起见,我想知道对于这样的任务是否还有另一种更好的解决方案。也许是另一个我不知道的更优化的数据结构,一个现有的类已经设法以更好的方式做到这一点。

就是这样,谢谢你的建议!

标签: pythondictionarydata-structures

解决方案


您可以使用嵌套的defaultdict

from collections import defaultdict as dd

dictionary = dd(lambda: dd(int))

如果您将所述数据结构传递给您的函数,则该函数可以简单地是:

def addNewValue(dictionary, month, country, valueToAdd):
    dictionary[month][country] += valueToAdd

推荐阅读