'Update item in dict comprehension python [duplicate]

words = ['rocky','mahesh','surendra','mahesh','rocky','mahesh','deepak','mahesh','mahesh','mahesh','surendra']

words_count = {}
for word in words:
    words_count[word] = words_count.get(word, 0) + 1

print(words_count)
# Expected Output
# {'rocky': 2, 'mahesh': 6, 'surendra': 2, 'deepak': 1}

In this example, I just want to modify value of dict key while dict comprehension

Note: not looking other way to find occurrence/count of each key in dict.



Solution 1:[1]

You can use collections.Counter:

from collections import Counter

words_count = Counter(words)

Solution 2:[2]

A short, simple, one-liner code:

{i:words.count(i) for i in words}

Here, we create a dictionary based on the count of the word.
Gives:

{'rocky': 2, 'mahesh': 6, 'surendra': 2, 'deepak': 1}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Joshua