通过循环取消Python字典?

时间:2014-03-04 13:17:49

标签: python dictionary python-3.3 pickle

我是Python的新手,我想要实现的是腌制字典,然后使用某种形式的循环(如果我的术语不正确,请道歉!)打印文件中的所有分数。

我正在使用Python 3.3.3,这是我的尝试,用户输入一个名称和一个分数,首先保存到文件然后我尝试打印它。但是我无法打印分数。

import pickle

# store the scores in a pickled file
def save_scores(player, score):    

    f = open("high_score.dat", "ab")
    d = {player:score}
    pickle.dump(d, f)
    f.close

# print all the scores from the file     
def print_scores():

     # this is the part that I can't get to work!
     with open("high_score.dat", "r") as f:
        try:
            for player, score  in pickle.load(f):
                print("Player: ", player, " scored : ", score)
        except EOFError:
            pass    
    f.close

def main():

    player_name = input("Enter a name: ")
    player_score = input("Enter a score: ")

    save_scores(player = player_name, score = player_score)
    print_scores()


main()

input("\nPress the Enter key to exit")   

我有谷歌和搜索Stackoverflow的类似问题但我必须使用错误的条款,因为我还没有找到解决方案。

提前致谢。

3 个答案:

答案 0 :(得分:2)

pickle.load(f)将返回字典。如果你迭代字典,它会产生键,而不是键值对。

要生成键值值paris,请使用items()方法(如果使用Python 2.x,请使用iteritems()方法):

for player, score  in pickle.load(f).items():
    print("Player: ", k, " scored : ", v)

要获取多个词典,您需要循环:

with open("high_score.dat", "r") as f:
    try:
        while True:
            for player, score  in pickle.load(f).items():
                # print("Player: ", k, " scored : ", v) # k, v - typo
                print("Player: ", player, " scored : ", score)
    except EOFError:
        pass    

顺便说一句,如果你使用with语句,则不需要自己关闭文件。

# f.close # This line is not necessary. BTW, the function call is missing `()`

答案 1 :(得分:1)

pickle.load将返回您的字典({player:score}

此代码:

for player, score  in pickle.load(f):

将尝试将返回的值解压缩为元组。 此外,由于您忽略了异常,因此很难分辨出错误。

答案 2 :(得分:1)

我做了一些修复,让你的代码在Python 2下运行(没有Python 3可用,对不起)。几个地方都改变了。这里有一些注意事项:

#!/bin/python2
import pickle

# store the scores in a pickled file
def save_scores(player, score):    
    f = open("high_score.dat", "wb")  # "wb" mode instead of "ab" since there is no obvious way to split pickled objects (surely you can make it, but it seems a bit hard subtask for such task)
    d = {player:score}
    pickle.dump(d, f)
    f.close()  # f.close is a method; to call it you should write f.close()

# print all the scores from the file     
def print_scores():

     # this is the part that I can't get to work!
     with open("high_score.dat", "rb") as f:  # "rb" mode instead of "r" since if you write in binary mode than you should read in binary mode
        try:
            scores = pickle.load(f)
            for player, score  in scores.iteritems():  # Iterate through dict like this in Python 2
                print("Player: ", player, " scored : ", score)  # player instead of k and score instead of v variables
        except EOFError:
            pass    
     # f.close -- 1. close is a method so use f.close(); 2. No need to close file as it is already closed after exiting `where` expression.

def main():

    player_name = raw_input("Enter a name: ")  # raw_input instead of input - Python 2 vs 3 specific
    player_score = raw_input("Enter a score: ")

    save_scores(player = player_name, score = player_score)
    print_scores()


main()

raw_input("\nPress the Enter key to exit")