首页 > 解决方案 > 如何将带有字数的列表转换为字典

问题描述

我想用一个字符串制作字典,并计算该字符串的单词。这就是我所做的,但它给了我一个错误!

book_text = "if it exists it should print"
for word in book_text:
    word = book_text.split(" ")
print(word)

dictionary = {}
for i in word:
    dictionary.values(i)
    dictionary.keys(word.count(i))
    print(dictionary)

错误说值需要多个元素

标签: pythonpython-3.x

解决方案


如果键不存在,您可以使用setdefault方法将键的值设置为 0。如果键已经存在,它将返回值。

初始变量

s = 'I want to make a dictionary using a string and count the words of that string'
a = [1, 2, 3, 2, 3]
d = {}

构建字典的不同方法

for xx in s:
    d[xx] = 1 + d.get(xx, 0)

print(d)

另外,如果您不想使用该库,那么您可以这样做。

for xx in s:  #same way we can use a
    if xx not in d:
        d[xx] = 1
    else:
        d[xx]+ = 1

我们可以再次使用更快的 Counter。

from collections import Counter
s = list(s)
print(Counter(s))

推荐阅读