python字典如何使用if else条件?

时间:2019-07-08 05:15:43

标签: 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

1 个答案:

答案 0 :(得分:2)

如果您只需要检查化合物的值并且只有一本词典,则可以这样做

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