【问题标题】:Python: printing dictionary values in a functionPython:在函数中打印字典值
【发布时间】:2018-05-23 03:32:21
【问题描述】:

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

 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))

【问题讨论】:

    标签: python function loops dictionary


    【解决方案1】:

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

    这里有一个例子来证明你不能复制一个字典键。

    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,看来dict不是你想要的数据结构。如果您的目标是列出允许的成绩值,请改用list

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

    【讨论】:

    • 我不知道您不能在字典中使用相同的键。谢谢!
    • 哦,好吧,我会毫不犹豫地将其标记为已接受。如果你不介意的话,还有一个问题。如果改为使用等级值列表和带有值的字典。调用它们时如何组合它们?
    • @MikaLand 如果您想从列表中打印成绩,您的函数实际上可以如下所示:def owls_grades (grades): print(*grades)。或者,如果您不喜欢或还不了解此语法,只需从现有函数中删除 .values。
    • 喜欢 *args 还是 **kwargs?
    • 我鼓励你尝试一下。一个会工作,另一个不会
    【解决方案2】:

    这里的问题是定义的字典具有相同的键。 Python 中的字典被视为“关联数组”。与由一系列数字索引的序列不同,字典由键索引,键可以是任何不可变类型;字符串和数字总是可以作为键。如果元组仅包含字符串、数字或元组,则元组可以用作键;如果元组直接或间接包含任何可变对象,则不能将其用作键。您不能将列表用作键,因为可以使用索引分配、切片分配或 append() 和 extend() 等方法就地修改列表。

    使用字典背后的想法是进行快速搜索,而不是顺序搜索。您应该有一个唯一的键,您可以使用它搜索键以获取相应的值。如果用不同的值定义相同的键,那么使用字典的目的就失效了。

    >>>
    >>> dictionary = { 'key1' : 'value1', 'key2': 'value2'}
    >>> dictionary['key1']
    'value1'
    >>> dictionary['key2']='value21'
    >>> dictionary
    {'key2': 'value21', 'key1': 'value1'}
    >>>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2011-10-07
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多