从OrderedDict获取密钥计数,其中密钥是元组

时间:2014-08-28 18:06:39

标签: python python-2.7 counter ordereddictionary

我有一本这样的词典:

my_dict=collections.OrderedDict([((123, 1), 'qwe'), ((232, 1), 'asd'), ((234, 2), 'zxc'), ((6745, 2), 'aaa'), ((456, 3), 'bbb')])

元组的组合总是唯一的,我想保持插入的顺序,因此OrderedDict。在dict中我有超过10K的物品。如何有效地维护一个计数器,该计数器给出元组中第二个元素的计数?基本上,每当我想要添加/删除密钥中的项目时,我都需要知道计数。现在我只是遍历my_dict并每次都获得计数器,但这样做似乎非常昂贵。

在上面的示例中,我希望输出为:

1:2 # As in 1 occurs 2 times 
2:2
3:1

现在我执行以下操作:

from collections import OrderedDict, Counter
my_dict = OrderedDict()
my_dict[(123,1)] = 'qwe'
my_dict[(232,1)] = 'asd'
my_dict[(234,2)] = 'zxc'
my_dict[(6745,2)] = 'aaa'
my_dict[(456,3)] = 'bbb'
cnt = []
for item in my_dict.keys():
    cnt.append(item[1])
print Counter(cnt)

我不确定这是否是最好的方法,但有没有办法覆盖=运算符和pop函数,这样每次我这样做时它都会增加或减去一个计数操作

1 个答案:

答案 0 :(得分:3)

CounterOrderedDict很好地协作可能需要一些子类化。这可能有用(我只实施了__setitem____getitem__,但如果您想要更强大的实施,请告诉我们):

import collections

class CountedOrderedDict(collections.OrderedDict):
    def __init__(self, *args, **kwargs):
        self.counter = collections.Counter()
        super(CountedOrderedDict, self).__init__(*args, **kwargs)

    def __delitem__(self, key):
        super(CountedOrderedDict, self).__delitem__(key)
        self.counter[key[1]] -= 1

    def __setitem__(self, key, value):
        if key not in self:
            self.counter[key[1]] += 1

        super(CountedOrderedDict, self).__setitem__(key, value)

使用示例:

>>> my_dict = CountedOrderedDict({(123,1): 'sda', (232,1) : 'bfd', (234,2) : 'csd', (6745,2) : 'ds', (456,3) : 'rd'})
>>> my_dict.counter
Counter({'1': 2, '2': 2, '3': 1})
>>> del my_dict[(123,1)]
>>> my_dict.counter
Counter({'2': 2, '1': 1, '3': 1})
>>> my_dict[(150,1)] = "asdf"
>>> my_dict.counter
Counter({'1': 2, '2': 2, '3': 1})

这是一个更通用的CountedOrderedDict实现,它将关键函数作为参数。

import collections

class CountedOrderedDict(collections.OrderedDict):
    def __init__(self, key=lambda k: k, *args, **kwargs):
        self.counter = collections.Counter()
        self.key_transform = key
        super(CountedOrderedDict, self).__init__(*args, **kwargs)

    def __delitem__(self, key):
        super(CountedOrderedDict, self).__delitem__(key)
        self.counter[self.key_transform(key)] -= 1

    def __setitem__(self, key, value):
        if key not in self:
            self.counter[self.key_transform(key)] += 1

        super(CountedOrderedDict, self).__setitem__(key, value)

根据您的需要,您可以这样实例化:

my_dict = CountedOrderedDict(key=lambda k: k[1])