有没有更有效的方法来增加字典中每个键的值?

时间:2020-06-13 16:40:08

标签: python dictionary

我正在尝试增加字典中所有键的值。我已经将嵌套列表合并为一个字典,最初将每个子列表的第一个元素作为键,并将0用作我所有键的值。

test_list = [['a', 'good'], ['a', 'pretty good'], ['a', 'extremely good'], ['b', 'good'], ['c', 'good']]
res = {sub[0]: 0 for sub in test_list}

现在,我想在嵌套列表中找到所有出现的子字符串“ good”,并增加字典中相应键的值。我的代码如下:

for i in res:
    for sublist in test_list:
        if i == sublist[0]:
            if ('good' in sublist[1]):
                res[i] += 1

我的代码为我提供了{'a':3,'b':1,'c':1}的正确输出,但是如果我有一个非常广泛的嵌套列表,那么我也会有一个很大的字典和2个“ for”循环使我的代码效率低下,而且标题很低。有更有效的方法吗?

2 个答案:

答案 0 :(得分:2)

如果您准备使用defaultdict,则:

from collections import defaultdict

test_list = [['a', 'good'], ['a', 'pretty good'], ['a', 'extremely good'], ['b', 'good'], ['c', 'good']]

res = defaultdict(int)

for key, value in test_list:
    res[key] += ('good' in value)


print(res)
# defaultdict(int, {'a': 3, 'b': 1, 'c': 1})

否则:

res = {}

for key, value in test_list:
    res[key] = res.get(key, 0) + ('good' in value)

print(res)
# {'a': 3, 'b': 1, 'c': 1}

答案 1 :(得分:2)

这也可以使用单个for循环来完成。

for sublist in test_list:
    if 'good' in sublist[1]:
        res[sublist[0]] +=1

print(res)

输出:-

{'a': 3, 'b': 1, 'c': 1}
相关问题