-3
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.

3 Answers3

3

You can use collections.Counter:

from collections import Counter

words_count = Counter(words)
kederrac
  • 16,819
  • 6
  • 32
  • 55
1

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}
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
1

You could count that without using any import and using as few .counts as possible following way:

words = ['rocky','mahesh','surendra','mahesh','rocky','mahesh','deepak','mahesh','mahesh','mahesh','surendra']
words_count = {i:words.count(i) for i in set(words)}
print(words_count)  # {'surendra': 2, 'mahesh': 6, 'rocky': 2, 'deepak': 1}

Converting list to set will result in unique values.

Daweo
  • 31,313
  • 3
  • 12
  • 25