用新键初始化python字典

时间:2016-03-26 20:51:38

标签: python dictionary

如何使用未预先确定的键初始化python词典?

如果我只是用dict = {}初始化字典,一旦我尝试用新的键值对填充它就会给我一个关键错误。

解决方法是尝试 - 尝试 - 以便它首先尝试访问现有密钥,或者如果前一个密钥失败,则为新密钥初始化字典。一个具体的例子是计算文本中的单词(这个代码示例将导致Key Error):

wordcount = {}
for word in text:
     wordcount[word] += 1

6 个答案:

答案 0 :(得分:2)

使用您正在执行的方法,应该执行此操作的方式是使用in关键字检查密钥是否已存在。如果确实如此,则执行增量,否则只需指定1.如下:

wordcount = {}
text = ["this", "is", "my", "sentence", "yes", "it", "is", "my", "stuff"]
for word in text:
    if word in wordcount:    
        wordcount[word] += 1
    else:
        wordcount[word] = 1

print(wordcount)

# {'yes': 1, 'stuff': 1, 'sentence': 1, 'my': 2, 'is': 2, 'this': 1, 'it': 1}

根据您的评论,如果您实际使用defaultdict模块中的collectionsdocumentation),则可以避免这种情况。您只需设置default值对字典条目的影响,然后继续+=。例如:

from collections import defaultdict
my_dict = defaultdict(int)
text_list = ["this", "is", "my", "sentence", "yes", "it", "is", "my", "stuff"]

for text in text_list:
    my_dict[text] += 1

print(my_dict)

# defaultdict(<class 'int'>, {'sentence': 1, 'this': 1, 'is': 2, 'my': 2, 'yes': 1, 'it': 1, 'stuff': 1})

现在,如果您只是尝试计算文字中的单词,那么已经有一些内置的功能可以从Counter模块(documentation)中为您调用collections 。这将保留所有相似元素的计数。观察这个例子:

from collections import Counter
text = ["this", "is", "my", "sentence", "yes", "it", "is", "my", "stuff"]    
my_count_dict = Counter(text)

print(my_count_dict)

Counter({'my': 2, 'is': 2, 'stuff': 1, 'this': 1, 'it': 1, 'sentence': 1, 'yes': 1})

按照最常见的顺序注意输出。如果您需要获取最常用的字词,请在其上调用most_common

print(my_count_dict.most_common(1))
# [('my', 2)]

答案 1 :(得分:2)

无需使用预定义值初始化您的dict。

您也不需要任何尝试/除外,只需使用默认类型设置为defaultdict的Python int

from collections import defaultdict
wordcount = defaultdict(int)
for word in text:
    wordcount[word] += 1

但是,如果你只需要计算列表中的单词,Python也会在集合中有一个名为Counter的辅助类。

答案 2 :(得分:0)

在尝试增加密钥之前,您需要确保初始化密钥(+=1)。试试这个:

wordcount = {}
text = ["word","foo","word","word","bar","bar","word","something"]
for word in text:
    if word in wordcount:  # tests to see if the key exists already
        wordcount[word] += 1
    else:  # initializes the key to 1
        wordcount[word] = 1
print(wordcount)
# prints {'bar': 2, 'word': 4, 'something': 1, 'foo': 1}

答案 3 :(得分:0)

首先需要为你的词典添加键值对。

wordcount = {}
for word in text:
    if word not in wordcount:
        wordcount[word] = 0
    wordcount[word] += 1

答案 4 :(得分:0)

如果我在这里理解你的目标是得到一个dict的单词:count mapping,那么你也可以用字典理解(以idjaw为例):

>>> text = ["this", "is", "my", "sentence", "yes", "it", "is", "my", "stuff"]
>>> 
>>> {c:text.count(c) for c in text}
{'it': 1, 'my': 2, 'yes': 1, 'is': 2, 'stuff': 1, 'this': 1, 'sentence': 1}

或者来自Counter模块的collections也可以完成这项工作:

>>> from collections import Counter
>>> 
>>> c = Counter()
>>> 
>>> for word in text:
        c[word] += 1


>>> c
Counter({'my': 2, 'is': 2, 'it': 1, 'yes': 1, 'stuff': 1, 'this': 1, 'sentence': 1})
>>> 

答案 5 :(得分:0)

word_count = {}
for word in text:
    word_count[word] = word_count.setdefault(word, 0) + 1
相关问题