简体   繁体   English

获取嵌套字典中的值计数

[英]Get the count of the values in a nested dictionary

I've a nested dictionary such as this: 我有一个这样的嵌套字典:

from collections import defaultdict, OrderedDict
dict = defaultdict(lambda:OrderedDict())
dict[1]['ab'] = 2343
dict[1]['ac'] = 6867
dict[1]['ad'] = 2345
dict[2]['sa'] = 2355
dict[2]['sg'] = 4545
dict[2]['sf'] = 2445
dict[3]['df'] = 9988

I want the count of the values for each keys. 我想要每个键的值计数。 The count of each item will be run through an algorithm to determine where the next value needs to be added/removed. 每个项目的计数将通过算法进行计算,以确定下一个值需要在何处添加/删除。 Right now I've this: 现在我有这个:

count = {}
for k, v in dict.items():
    count[k] = len(v)

Scaling is important here as I'm dealing with very large databases. 在这里扩展很重要,因为我正在处理非常大的数据库。 I've to have the count every time I do something with the dictionary and if I'm accessing it a million times, I'd have to create count each time. 每次对字典执行某项操作时,我都必须具有计数,如果我要访问一百万次,则必须每次都创建count Is there a more efficient/pythonic way to do this? 有没有更有效的/ python方式来做到这一点? May be create a custom class similar to this that keeps a count for each item as and when it is created/removed? 可以创建一个与此类似的自定义类,该类在创建/删除项目时对其进行计数吗?

Create your own class the inherits the dict class and add the count array that you need and have the new add/remove functions update it accordingly. 创建您自己的类,该类继承dict类并添加所需的count数组,并使新的add / remove函数相应地对其进行更新。 Add a function that given a key returns the count and that way you can get the updated count without any extra time wasted other than the time you already have to spend in adding/removing from the dictionary. 添加给定键的函数将返回计数,这样您就可以获取更新后的计数,而不会浪费任何时间,而不必花时间在字典中添加/删除。 There are examples of how to subclass and override the add/remove functions here 还有的如何继承和覆盖添加/删除功能的例子在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM