简体   繁体   English

在Python中将字典值动态初始化为零

[英]Dynamic initialization of a dictionary value to zero in Python

I am assigning the dictionary keys on the fly after detecting what language a predicted string belongs to and I was wondering how to initialize it to zero. 在检测到预测字符串属于哪种语言之后,我正在动态分配字典键,我想知道如何将其初始化为零。

from textblob import TextBlob


correct = {}     

    for i in max_dist_indices:          
...
        correct[TextBlob(predicted_labels[j]).detect_language()] += 1*(predicted_labels[i] == labels[i])

Where d etect.language() returns a string according to the language in the predicted labels, ' en ' for English, which serves as the key. 其中d etect.language()根据预测的标签中的语言返回字符串,“ en ”代表英语,它是键。 Any ideas how this could be done? 任何想法如何做到这一点?

You can use the dict.get method: 您可以使用dict.get方法:

language = TextBlob(predicted_labels[j]).detect_language()
correct[language] = correct.get(language, 0) + (predicted_labels[i] == labels[i])

or you can initialize correct as defaultdict(int) instead: 或者你可以初始化correctdefaultdict(int)代替:

from collections import defaultdict
correct = defaultdict(int)
correct[language] += predicted_labels[i] == labels[i]

With dictionaries, you have key-value pairs. 使用字典,您可以有键/值对。 When you say you want to initialise a key to 0, I think you mean you want to initialise its value to 0. 当您说要将键初始化为0时,我想您是说要将其值初始化为0。

Assuming that 1*(predicted_labels[i] is not equal to labels[i]) and will therefore return 0, the following should give what you want: 假设1*(predicted_labels[i]不等于labels[i])并因此将返回0,则以下内容应为您所要:

correct[TextBlob(predicted_labels[j]).detect_language()] = 1*(predicted_labels[i] == labels[i])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM