更新字典理解中的项目 python

Update item in dict comprehension python

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}

在这个例子中,我只想在字典理解时修改字典键的值

注意:没有寻找其他方法来查找字典中每个键的 occurrence/count。

一个简短的单行代码:

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

在这里,我们根据单词的计数创建字典。
给出:

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

您可以使用 collections.Counter:

from collections import Counter

words_count = Counter(words)

您可以在不使用任何导入的情况下使用尽可能少的 .counts 来计算,方法如下:

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}

list 转换为 set 将产生唯一值。