通过循环取消勾选Python字典?

通过循环取消勾选Python字典?,python,dictionary,python-3.3,pickle,Python,Dictionary,Python 3.3,Pickle,我对Python非常陌生,我试图实现的是对字典进行pickle处理,然后使用某种形式的循环(如果术语不正确,请道歉!)打印文件中的所有分数 我使用的是Python3.3.3,下面是我的尝试,用户输入一个名称和分数,该名称和分数首先保存到一个文件中,然后我尝试打印它。但是我无法打印分数 import pickle # store the scores in a pickled file def save_scores(player, score): f = open("high

我对Python非常陌生,我试图实现的是对字典进行pickle处理,然后使用某种形式的循环(如果术语不正确,请道歉!)打印文件中的所有分数

我使用的是Python3.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,寻找类似的问题,但我一定是用错了词,因为我还没有找到解决方案

提前感谢。

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

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

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

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    
顺便说一句,如果您对语句使用
,您不需要自己关闭文件

# f.close # This line is not necessary. BTW, the function call is missing `()`
pickle.load(f)
将返回一个字典。如果迭代字典,它将生成键,而不是键值对

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

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

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    
顺便说一句,如果您对
语句使用
,您不需要自己关闭文件

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

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

此代码:

for player, score  in pickle.load(f):
将尝试将返回值解包为元组。
另外,由于您忽略了异常,因此很难判断出发生了什么错误。

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

此代码:

for player, score  in pickle.load(f):
将尝试将返回值解包为元组。
另外,由于您忽略了异常,因此很难判断出哪里出了问题。

我已经做了一些修复,使您的代码在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")

我已经做了一些修复,使您的代码在Python2下工作(对不起,没有Python3可用)。换了几个地方。下面是一些注释:

#!/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")

谢谢你的全面回答!我已经更新了我的问题,表明我正在使用3.3.3版。我还更新了代码以反映这些更改,但是我现在看到了以下错误:文件“H:/Sandbox/python/save_and_print_scores.py”,第19行,在print_scores for player中,在pickle.load(f).items()中得分:TypeError:“str”不支持缓冲区interface@IanCarpenter,你能把
high_score.dat
文件上传到什么地方吗?@iancarcenter,我在你的代码中发现了一个输入错误。在下一行中,
k
v
应替换为:
print(“Player:,k,“scored:,v”)
。相应地更新了答案。@IANCARPENT,
f.close
save_scores
功能中也缺少
()
。如果没有括号,它将不会调用
close
method.@iancarcenter,没问题。快乐Python编程:)谢谢你的全面回答!我已经更新了我的问题,表明我正在使用3.3.3版。我还更新了代码以反映这些更改,但是我现在看到了以下错误:文件“H:/Sandbox/python/save_and_print_scores.py”,第19行,在print_scores for player中,在pickle.load(f).items()中得分:TypeError:“str”不支持缓冲区interface@IanCarpenter,你能把
high_score.dat
文件上传到什么地方吗?@iancarcenter,我在你的代码中发现了一个输入错误。在下一行中,
k
v
应替换为:
print(“Player:,k,“scored:,v”)
。相应地更新了答案。@IANCARPENT,
f.close
save_scores
功能中也缺少
()
。如果没有括号,它将不会调用
close
method.@iancarcenter,没问题。快乐Python编程:)