python-3.x - 如何在Python字典中使用if else条件?

标签 python-3.x

我是 python 新手。我有这样的字典变量:

vs={'neg': 0.0, 'neu': 0.254, 'pos': 0.746, 'compound': 0.8316}

我想使用 if else 条件并执行以下操作,如何执行此操作

positive sentiment: compound score >= 0.05
neutral sentiment: (compound score > -0.05) and (compound score < 0.05)
negative sentiment: compound score <= -0.05

vs = {'neg': 0.0, 'neu': 0.254, 'pos': 0.746, 'compound': 0.8316}
for k, v in vs.items():
    if k['compound'] >= 0.5:
        print('positive')

错误:

TypeError: string indices must be integers

最佳答案

如果您只需要检查compound的值并且您只有一个字典,您可以这样做

if vs['compound'] >= 0.05:
    print('positive')
elif vs['compound'] <= -0.05:
    print('negative')
else:
    print('neutral')

关于python-3.x - 如何在Python字典中使用if else条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56928766/

相关文章:

python-3.x - 使用列 Pandas 的特定单词提取行直到特定行

python - 无法在Python中将字符串转换为日期时间

python - 如何从多维数组中删除值之和等于0的元素?

python Selenium : stale element reference: element is not attached to the page document

python - 如何打印具有相似字符串的值?

python - 如何从 python 字典中返回特定信息?

python - 从 HTML 标签中包含的一系列字符串和不带标签的字符串中提取文本

python - 为我的程序在 Python 中将 int 转换为枚举?

python - 如何获取数组内部数组的最小值和最大值?

python-3.x - 发送多个参数到flask-restplus