从字典中添加值

时间:2014-12-02 18:53:20

标签: python-3.x

我在尝试从字典中添加每个播放器的值时收到错误消息,可能是因为我的字典中的值是字符串但我不确定。代码是:

with open("players.dat") as f:
    group = []
    for line in f:
        fields = line.split()
        group.append( (fields[0], int(fields[1])) )
    print(group)

from collections import deque

player_stats = {}
with open("players.dat") as f:
    for line in f:
        name, score = line.split()
        player_stats.setdefault(name, deque(maxlen=3))
        player_stats[name].append(score)
        sum(player_stats.values())

print(player_stats)

数据文件是:

rooney 12
rooney 23
rooney 56
rooney 27
ronaldo 14
ronaldo 34
messi 23
messi 45
messi 12
messi 56

1 个答案:

答案 0 :(得分:0)

你是对的,你的dict中的值是字符串而不是整数。在这段代码中

for line in f:
    name, score = line.split()
    player_stats.setdefault(name, deque(maxlen=3))
    player_stats[name].append(score) # this line
    sum(player_stats.values())

将标记的行更改为

player_stats[name].append(int(score))

你应该全力以赴。