python - 我不确定如何让我的字典打印我想要的信息。 Python 3.1

标签 python hash dictionary

请温柔点,我对编程很陌生,并且只拥有一本给我一些糟糕指导的书(《Head First 编程》)。这是我在 Python IDLE 中的代码:

scores = {}

scores[8.45] = 'Zach'
scores[9.12] = 'Juan'
scores[8.31] = 'Aaron'
scores[8.05] = 'Aideen'
scores[8.65] = 'Johnny'
scores[7.81] = 'Stacey'

for key in scores.keys():
    print(scores[key] + ' had a score of ' + scores[???])

该程序的目的是打印一个包含参赛者姓名及其相应分数的列表,但我不知道此时我做错了什么或对了:/

编辑:谢谢你们。在您的帮助下,我将代码编辑为工作顺序,如果您对此感兴趣,它是:

scores = {}

scores['Zach'] = 8.45

scores['Juan'] = 9.12

scores['Aaron'] = 8.31

scores['Aideen'] = 8.05

scores['Johnny'] = 8.65

scores['Stacey'] = 7.81

for key in scores.keys():    
    print(str(key), ' had a score of ' , scores[key])

最佳答案

您可以使用 {...}.items() 迭代器,如下所示:

for score,name in scores.items():
    print('{name} had a score of {score}'.format(**locals()))

但是,您的字典顺序错误。例如,如果扎克和胡安的分数相同,均为 9.10,该怎么办?然后,编写 scores[9.10]='Zach' Scores[9.10]='Juan' 将覆盖 Zach!键应该是名称。

你可以这样写:

scores['Zach'] = 8.45
scores['Juan'] = 8.45
...

郑重声明,以下是我从头开始的操作方法:

def parseScores(string):
    scores = {}
    for line in string.splitlines():
        if line.strip():
            name,score = line.strip().split()
            scores[name] = float(score)
    return scores

data = """
    Zach 8.45
    Juan 9.12
    Aaron 2.2
    Aideen 2.2
    Johnny 2.2
    Stacey 7.81
"""

scores = parseScores(data)
for name,score in scores.items():
    print('{name} had a score of {score}'.format(**locals()))

关于python - 我不确定如何让我的字典打印我想要的信息。 Python 3.1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6405992/

相关文章:

python - 在 Pandas 中使用列名作为新属性

python - 从 extjs 页面发送 json 对象到后端

hash - Python 与 STM32 内置 HASH 设备中的 SHA256 摘要不一致

perl - 按顺序遍历哈希

python - 让 beautifulsoup 运行 python

python - 如何在句子列表中的单词和左括号之间创建空格

java - Java外部文件的哈希函数

python - 向字典添加新键会用新键值覆盖所有以前存储的键

python - 无法使用唯一的第一个键确定性地更新嵌套字典

java - java中图形操作的实用程序