字典和默认值
- 2025-02-12 10:04:00
- admin 原创
- 54
问题描述:
假设connectionDetails
是一个 Python 字典,那么重构此类代码的最好、最优雅、最“Python 化”的方法是什么?
if "host" in connectionDetails:
host = connectionDetails["host"]
else:
host = someDefaultValue
解决方案 1:
像这样:
host = connectionDetails.get('host', someDefaultValue)
解决方案 2:
您还可以defaultdict
像这样使用:
from collections import defaultdict
a = defaultdict(lambda: "default", key="some_value")
a["blabla"] => "default"
a["key"] => "some_value"
您可以传递任何普通函数来代替 lambda:
from collections import defaultdict
def a():
return 4
b = defaultdict(a, key="some_value")
b['absent'] => 4
b['key'] => "some_value"
解决方案 3:
虽然.get()
这是一个很好的习语,但它比以下速度慢if/else
(并且比try/except
大多数时候可以预期字典中存在键时的速度慢):
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
... stmt="try:
a=d[1]
except KeyError:
a=10")
0.07691968797894333
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
... stmt="try:
a=d[2]
except KeyError:
a=10")
0.4583777282275605
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
... stmt="a=d.get(1, 10)")
0.17784020746671558
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
... stmt="a=d.get(2, 10)")
0.17952161730158878
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
... stmt="if 1 in d:
a=d[1]
else:
a=10")
0.10071221458065338
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
... stmt="if 2 in d:
a=d[2]
else:
a=10")
0.06966537335119938
解决方案 4:
对于多个不同的默认值,请尝试以下操作:
connectionDetails = { "host": "www.example.com" }
defaults = { "host": "127.0.0.1", "port": 8080 }
completeDetails = {}
completeDetails.update(defaults)
completeDetails.update(connectionDetails)
completeDetails["host"] # ==> "www.example.com"
completeDetails["port"] # ==> 8080
解决方案 5:
这并不是确切所要求的问题,但是 Python 字典中有一种方法:dict.setdefault
host = connectionDetails.setdefault('host',someDefaultValue)
但是,如果键尚未定义,则此方法会将的值设置connectionDetails['host']
为,这与问题所问的不同。someDefaultValue
`host`
解决方案 6:
(这是迟来的答案)
另一种方法是将该dict
类子类化并实现该__missing__()
方法,如下所示:
class ConnectionDetails(dict):
def __missing__(self, key):
if key == 'host':
return "localhost"
raise KeyError(key)
例子:
>>> connection_details = ConnectionDetails(port=80)
>>> connection_details['host']
'localhost'
>>> connection_details['port']
80
>>> connection_details['password']
Traceback (most recent call last):
File "python", line 1, in <module>
File "python", line 6, in __missing__
KeyError: 'password'
解决方案 7:
您可以使用dict.get()
默认值。
d = {"a" :1, "b" :2}
x = d.get("a",5)
y = d.get("c",6)
# This will give
# x = 1, y = 6
# as the result
由于“a”在键中,x = d.get("a",5)
将返回关联值1
。由于“c”不在键中,y = d.get("c",6)
将返回默认值6
。
解决方案 8:
测试@Tim Pietzcker 对 Python 3.3.5 的 PyPy (5.2.0-alpha0) 中情况的怀疑,我发现.get()
和if
/else
方式确实表现相似。实际上,在 if/else 情况下,如果条件和赋值涉及相同的键,似乎甚至只有一次查找(与最后一种情况相比,有两次查找)。
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="try:
a=d[1]
except KeyError:
a=10")
0.011889292989508249
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="try:
a=d[2]
except KeyError:
a=10")
0.07310474599944428
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="a=d.get(1, 10)")
0.010391917996457778
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="a=d.get(2, 10)")
0.009348208011942916
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="if 1 in d:
a=d[1]
else:
a=10")
0.011475925013655797
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="if 2 in d:
a=d[2]
else:
a=10")
0.009605801998986863
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="if 2 in d:
a=d[2]
else:
a=d[1]")
0.017342638995614834
解决方案 9:
您可以使用 lamba 函数作为一行代码来实现这一点。创建一个 connectionDetails2
像函数一样访问的新对象...
connectionDetails2 = lambda k: connectionDetails[k] if k in connectionDetails.keys() else "DEFAULT"
现在使用
connectionDetails2(k)
而不是
connectionDetails[k]
如果字典中的键是字典值,则返回该字典值k
,否则返回"DEFAULT"
解决方案 10:
我确信所有这些答案都是正确的,但这表明没有“好”的方法可以做到这一点。我一直使用字典而不是 case 语句,要添加默认子句,我只需调用以下函数:
def choose(choise, choises, default):
"""Choose a choice from the choises given
"""
return choises[choise] if choise in choises else default
这样我就可以使用普通字典而不需要特殊的默认子句等等。