Chew Kah Meng
Chew Kah Meng

Reputation: 227

Is there a more efficient way in incrementing values of every key in a dictionary?

I am trying to increment the values of all my keys in a dictionary. I have consolidated my nested list into a dictionary with the first element of each sublist as the key and 0 as the value for all my keys initially.

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

Now, I want to find all occurrences of the substring 'good' in my nested list and increment the value of the corresponding key in my dictionary. My code is as follows:

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

My code gives me the correct output of {'a': 3, 'b': 1, 'c': 1} but if I have a nested list which is extremely extensive, I will have a big dictionary as well and the 2 'for' loops makes my code really inefficient and TLE. Is there a more efficient way to do this?

Upvotes: 1

Views: 266

Answers (2)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

If you are prepared to use defaultdict then:

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})

Otherwise:

res = {}

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

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

Upvotes: 2

Dhaval Taunk
Dhaval Taunk

Reputation: 1672

This could be done using a single for loop as well.

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

print(res)

Output:-

{'a': 3, 'b': 1, 'c': 1}

Upvotes: 2

Related Questions