首页 > 解决方案 > Python:在函数中打印字典值

问题描述

所以我一直试图让它工作一段时间。我试图让这些字典通过一个函数列出两个字典中的所有值,如果这有意义的话。它运行但是它只打印两个字典的最终值的行。

 dictionary = {
    "grades": "O",
    "grades": "E",
    "grades": "A",
    "grades": "P",
    "grades": "D",
    "grades":"T",
}
dictionary_means = {
    "means": "O is for Outstanding!  You're top level now!",
    "means": "E is for Exceeds Expectations!  Very well done, almost 
perfect!",
    "means": "A for Acceptable.  That's okay, hopefully it'll get you 
somewhere...",
    "means": "P is for Poor.  Is that the best you can do?",
    "means": "D is for Dreadful.  Well at least it's not T...",
    "means": "T is for Troll.  Wow, you're an idiot."
}
def owls_grades (grades):
    for v in grades.values():
        print("Your grade is {}. ".format(v))




def owls_means (means):
    for value in means.values():
        print ("{}".format(value))

print (owls_grades(dictionary))
print (owls_means(dictionary_means))

标签: pythonfunctionloopsdictionary

解决方案


您正在复制字典键,因此每次重复键时都会覆盖该值。

这是一个示例,用于演示您不能复制字典键。

d = {'A': 1, 'A': 2}

print(d)  # {'A': 2}

相反,dictionary_means例如,应该看起来像这样。

dictionary_means = {
    "O": "O is for Outstanding!  You're top level now!",
    "E": "E is for Exceeds Expectations!  Very well done, almost 
perfect!",
    "A": "A for Acceptable.  That's okay, hopefully it'll get you 
somewhere...",
    "P": "P is for Poor.  Is that the best you can do?",
    "D": "D is for Dreadful.  Well at least it's not T...",
    "T": "T is for Troll.  Wow, you're an idiot."
}

至于dictionary,似乎 adict不是你想要的数据结构。list如果您的目标是列出允许的成绩值,请改用 a 。

["O", "E", "A", "P", "D", "T"]

推荐阅读