0

我有一本带有 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]

我得到错误

Traceback (most recent call last):
  File "happiest_state.py", line 61, in <module>
    processing()
  File "happiest_state.py", line 55, in processing
    readtweets(tweet_file, sent_dict)
  File "happiest_state.py", line 38, in readtweets
    current_score = float(sum(v))/len(v)
TypeError: unsupported operand type(s) for +: 'int' and 'unicode'

如果我从 切换vstate_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'
4

3 回答 3

2

遍历字典只返回键。你要:

for k, v in state_sentiment.iteritems():
于 2013-05-15T18:21:30.680 回答
1

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

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

您的代码运行(但不能正常工作),因为for k, v in state_sentiment实际上将每个键名拆分为单个字符:

>>> k, v = 'AB'
>>> k
'A'
>>> v
'B'

您想要做的是迭代键值项对

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) 
于 2013-05-15T18:27:37.763 回答
0
for k,v in state_sentiment.items():

是你想要的......否则你会得到 k="D",v="C"

print ["K:%s,V:%s"%(k,v) for k,v in state_sentiment]

因为遍历字典只会给你键(在这种情况下恰好是 2 个字母长(分别分配给 k,v))

于 2013-05-15T18:21:12.173 回答