【问题标题】:'None' returned from a call to '.get()' issue从调用“.get()”问题返回“无”
【发布时间】:2021-09-24 14:46:19
【问题描述】:

从对 .get() 的调用中返回 None 可能意味着未找到该键,或者在字典中的键处找到的值实际上是 None。

如果在布尔测试中没有找到并且解释为 0,那么我可以将返回值设置为什么?

为了写这个:

ages = {'Jim': 30, 'Pam': 28, 'Kevin': None}
person = input('Get age for: ')
age = ages.get(person, ?) #what need to be '?'

if age:
    print(f'{person} is {age} years old.')
else:
    print(f"{person}'s age is unknown.")

【问题讨论】:

  • 如果key:value 没有找到,你想返回一些东西吗?
  • @Sujay 我想用 .get(key, here) 返回 None 以外的东西,因为 .get(key) 默认返回 None 如果没有找到键,但 None 可以在关联的数据中一个关键,如我的例子。 .get(key, 0) 也是一个坏主意,因为 0 可以是与密钥相关联的有效数据,这意味着该人拥有

标签: python dictionary mapping nonetype


【解决方案1】:

您不需要使用.get。直接访问字典值即可。

像这样:

ages = {'Jim': 30, 'Pam': 28, 'Kevin': None}
person = input('Get age for: ')

try:
    age = ages[person]
    
    if age:
        print(f'{person} is {age} years old.')
    else:
        print(f"{person}'s age is unknown.")
except KeyError:
    print(f"Unknown person: {person}")
    

【讨论】:

  • 如果出现KeyError,您也可以捕获异常。
  • @Sujay 是的,我现在正在编辑
  • @MarkoBorković 所以在哪种情况下需要 .get() 方法? (你可以回答我:“google it”,我会接受的)
  • .get() 允许脚本继续运行并且不会引发 KeyError (这会停止脚本运行)。和写dictionary["Age"] or None基本一样,所以会隐式处理KeyError异常。
【解决方案2】:

在这种情况下,使用 try/except 会很有用:

ages = {'Jim': 30, 'Pam': 28, 'Kevin': None}
person = input('Get age for: ')
try:
    age = ages[person] #what need to be '?'
    if age:
        print(f'{person} is {age} years old.')
    else:
        print(f"{person}'s age is unknown.")
except KeyError:
    print(f'{person} not found in ages')

输出

Get age for: Jim
Jim is 30 years old.

Get age for: Kevin
Kevin's age is unknown.

Get age for: Bob
Bob not found in ages

【讨论】:

    【解决方案3】:
    ages = {'Jim': 30, 'Pam': 28, 'Kevin': None}
    person = input('Get age for: ')
    
    try:
        age = ages[person]
        
        if age:
            print(f'{person} is {age} years old.')
        else:
            print(f"{person}'s age is unknown.")
    except KeyError:
        print(f"{person} is not known.")
    

    【讨论】:

    • 但是你如何区分没有年龄的 kevin 和没有年龄的 seb 是字典?
    • @seb16120 如果 key 有效但 value 为 None,则返回 else 语句。 except KeyError 将被返回,如果密钥例如Seb 不存在。
    猜你喜欢
    • 1970-01-01
    • 2017-04-27
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 2018-05-24
    相关资源
    最近更新 更多