【问题标题】:What does the get method do on dictionaries? [closed]get 方法对字典有什么作用? [关闭]
【发布时间】:2018-05-03 01:24:20
【问题描述】:

我试图弄清楚get() 方法的作用。

def numbers_to_strings(argument):
switcher = {
    0: "zero",
    1: "one",
    2: "two",
}
return switcher.get(argument, "nothing")

-- 这个函数有什么作用?

【问题讨论】:

标签: python python-3.x dictionary


【解决方案1】:

如果密钥argumentswitcher 中,则.get() 方法返回密钥的value

如果key 不在dictionary 中,则该方法返回可选的“nothing”。

def numbers_to_strings(argument):
    switcher = {0: "zero",
                1: "one",
                2: "two"}
    return switcher.get(argument, "nothing")

使用字典中的key 调用上述函数:

>>> numbers_to_strings(0)
'zero'

并且,使用不在字典中的key 调用函数:

>>> numbers_to_strings(3)
'nothing'

您可以在dict.get()阅读有关该方法的信息

如果键在字典中,则返回键的值,否则返回默认值。如果未给出默认值,则默认为 None,因此此方法永远不会引发 KeyError。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    相关资源
    最近更新 更多