使每个密钥库在Python Dictionary中最多包含5个值

时间:2015-02-08 08:12:28

标签: python sorting dictionary


我最近为我的同事创建了一个猜谜游戏,作为学习Python 3.3x的项目。我一直将结果存储在一个用名称和分数格式化的文本文件中,用冒号分隔,如图所示......

Adam:12
Dave:25
Jack:13
Adam:34
Dave:23

感谢Padraic Cunningham,使用以下代码读取文本文件。

from collections import defaultdict
d = defaultdict(list)
with open('guesses.txt') as f:
    for line in f:
        name,val = line.split(":")
        d[name].append(int(val))

for k in sorted(d):
    print(k," ".join(map(str,d[k])))

现在的问题是,我想看看戴夫,亚当和杰克最近的四个分数。我想到的一种方法是以某种方式读取上面的列表并将其反转,以便它首先看到最新的结果。我想我可以先使用以下代码行反转字典:

inv_map = {v: k for k, v in d.items()}

但这不起作用,因为它返回错误:

TypeError: unhashable type: 'list'

由于我想存储4个最新结果,因此我需要确保每次新结果到达时都删除最旧的结果,并更新字典。

我怎样才能确保每个键只分配4个最大值?可以通过反转字典来完成吗?我试图看看其他问题是否遵循相同的原则,但我没有发现任何问题。

注意我看过itemgetter方法,但每个键都有多个值。

文本文件如下所示:

Adam:12
Dave:25
Jack:13
Adam:34
Dave:23
Jack:17
Adam:28
Adam:23
Dave:23
Jack:11
Adam:39
Dave:44
Jack:78
Dave:38
Jack:4    

1 个答案:

答案 0 :(得分:2)

您可以使用defaultdictdeque(maxlen=4)来处理。

import collections

d = collections.defaultdict(lambda: collections.deque(maxlen=4))
# defaultdict accepts as an argument a function that returns the default
#   state of the value of undefined keys. In this case we make an anonymous
#   function that returns a `collections.deque` with maxlen of 4.

# we could also do
# # import functools, collections
# # d = collections.defaultdict(functools.partial(collections.deque,
# #                                               maxlen=4))

with open('path/to/file.txt', 'r') as infile:
    for line in infile:
        player,score = line.strip().split(":")
        d[player].append(int(score))

然而,你最好只是创建这个数据结构来开始并挑选对象。

import pickle

# `highscores` is some previously populated high score dict

def save_scores(filename):
    with open(filename, 'w') as outfile:
        pickle.dump(highscores, outfile)

def load_scores(filename):
    with open(filename, 'r') as infile:
        highscores = pickle.load(infile)
    return highscores