python的unicode字典键问题

2024-09-26 18:15:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有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'

Tags: inpylen错误linecurrentfloatmax
3条回答
for k,v in state_sentiment.items():

是你想要的。。。否则,您将得到k=“D”,v=“C”

^{pr2}$

因为在字典上迭代只会得到键(在本例中正好是2个字母长(分别分配给k和v))

当你在字典上迭代时,实际上是在它的键上迭代:

>>> for a in {'b': 2, 'c': 3}:
...     print a
...
c
b

您的代码运行(但无法正常工作),因为for k, v in state_sentiment实际上将每个密钥名称拆分为单独的字符:

^{pr2}$

相反,您要做的是迭代键值项对:

for k, v in state_sentiment.items():
    ...

也可以跳过循环,使用max()执行此操作:

def key_func(state):
    return sum(state[1]) / float(len(state[1]))

happiest_state = max(state_sentiment.items(), key=key_func) 

迭代字典只返回键。你想要:

for k, v in state_sentiment.iteritems():

相关问题 更多 >

    热门问题