我有一个带有unicode键的字典,我似乎无法操作其中的元素
state_sentiment = {u'WA': [0.0], u'DC': [-2.0, 0.0], u'WI': [0.0, 0.0, 0.0], u'WV': [0.0], u'FL': [2.0, 0.0, -2.0, 0.0, 0.0, 1.0], u'OR': [6.0]}
for k,v in state_sentiment:
max_score = -10.00
happiest_state = ''
current_score = float(sum(v))/len(v)
if current_score > max_score:
max_score = current_score
happiest_state = state_sentiment[k]
我知道错误了
^{pr2}$如果我从v
切换到state_sentiment[k]
,仍然有一个错误
Traceback (most recent call last):
File "happiest_state.py", line 59, in <module>
processing()
File "happiest_state.py", line 53, in processing
readtweets(tweet_file, sent_dict)
File "happiest_state.py", line 36, in readtweets
current_score = float(sum(state_sentiment[k]))/len(state_sentiment[k])
KeyError: u'W'
是你想要的。。。否则,您将得到k=“D”,v=“C”
^{pr2}$因为在字典上迭代只会得到键(在本例中正好是2个字母长(分别分配给k和v))
当你在字典上迭代时,实际上是在它的键上迭代:
您的代码运行(但无法正常工作),因为
^{pr2}$for k, v in state_sentiment
实际上将每个密钥名称拆分为单独的字符:相反,您要做的是迭代键值项对:
也可以跳过循环,使用
max()
执行此操作:迭代字典只返回键。你想要:
相关问题 更多 >
编程相关推荐