gpt4 book ai didi

python - 为 dict 和 defaultdict 编写代码

转载 作者:太空宇宙 更新时间:2023-11-04 10:41:50 24 4
gpt4 key购买 nike

我有以下问题:

from collections import defaultdict

def give_it_to_me(d):
# This will crash if key 'it' does not exist
return d['it']

def give_it2_to_me(d):
# This will never crash, but does not trigger the default value in defaultdict
return d.get('it2')

d1 = defaultdict(int)
d2 = { 'it' : 55 }

print give_it_to_me(d1)
print give_it_to_me(d2)

print give_it2_to_me(d1)
print give_it2_to_me(d2)

正如您在评论中看到的那样,编写一个版本的 give_it_to_me 似乎是不可能的:

  1. 永远不会崩溃
  2. 触发defaultdict的默认值

还是我错了?

最佳答案

您可能需要在 give_it_to_me 函数中添加更多代码。

使用 try except 语句检查现有 key 。

例如:

def give_it_to_me(d):
# This won't crash if key 'it' does not exist in a normal dict.
# It returns just None in that case.
# It returns the default value of an defaultdict if the key is not found.
try:
return d['it']
except KeyError:
return None

关于python - 为 dict 和 defaultdict 编写代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20146822/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com