用于检查字典字典中是否存在值并采取相应操作的Pythonic方法

时间:2013-04-07 10:03:12

标签: python

我创建了一个字典词典:

from collections import defaultdict
d = defaultdict(dict)

现在我有一些字符串(让我们称之为set A),它们有一个字符串字典(作为键)和与之对应的整数(作为值)。因此,上述数据结构完全模拟了这些数据。

现在我想检查词典中是否存在与A中的键对应的字符串。如果它不存在,我想添加它并使其计数器1。如果它已经存在,我想增加计数器。

是否有pythonic方法可以做到这一点?

2 个答案:

答案 0 :(得分:4)

如果您拥有嵌套dict的密钥,则可以使用简单的in测试:

if somestring in d[key]:
    d[key][somestring] += 1
else:
    d[key][somestring] = 1

但您可以使用Counter代替:

from collections import defaultdict, Counter
d = defaultdict(Counter)

d[key][somestring] += 1

defaultdict类似,Counter为缺失密钥提供默认值,默认为0

计数器还有其他好处;而不是循环遍历一组字符串并逐个手动增加计数器,将整个序列传递给适当计数器的.update()方法:

d[key].update(sequence_of_strings)

并且Counter将为您计算所有内容。

Counter类是其他语言可能称为Multi-Set或Bag类型的类。它们也支持有趣的比较和算术运算,请确保您阅读该类型的文档。

答案 1 :(得分:1)

正如Lev Levitsky指出的那样,你想要的是使用Counter。例如,假设您有这个字符串:

>>> the_strings = [
...     ('a', ('the', 'strings', 'in', 'the', 'dict')),
...     ('b', ('other', 'strings', 'in', 'the', 'dict', 'in', 'your', 'question'))
... ]

并且您希望将'a'词典与该词的计数相关联,您可以这样做:

>>> my_dict = defaultdict(Counter)
>>> for key, strings in the_strings:
...     my_dict[key].update(strings)
... 
>>> my_dict['a']['the']
2
>>> my_dict['b']['in']
2
>>> my_dict['b']['question']
1

如果您想增加单个值,您可以执行以下操作:

>>> my_dict[the_string][the_word] += 1

或者您可以使用update方法自动增加可迭代中每个元素的数量:

>>> my_dict[the_string].update(iterable_of_elements)