字典和默认值

时间:2012-02-20 09:42:06

标签: python dictionary coding-style

假设connectionDetails是一个Python字典,那么重构代码的最佳,最优雅,最“pythonic”的方式是什么?

if "host" in connectionDetails:
    host = connectionDetails["host"]
else:
    host = someDefaultValue

8 个答案:

答案 0 :(得分:264)

像这样:

host = connectionDetails.get('host', someDefaultValue)

答案 1 :(得分:86)

您也可以像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"

答案 2 :(得分:24)

虽然.get()是一个很好的习惯用法,但它比if/else慢(并且如果在大多数情况下可以预期字典中存在密钥,则慢于try/except

>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", 
... stmt="try:\n a=d[1]\nexcept KeyError:\n a=10")
0.07691968797894333
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", 
... stmt="try:\n a=d[2]\nexcept KeyError:\n 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:\n a=d[1]\nelse:\n a=10")
0.10071221458065338
>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}", 
... stmt="if 2 in d:\n a=d[2]\nelse:\n a=10")
0.06966537335119938

答案 3 :(得分:18)

对于多种不同的默认值,请尝试:

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

答案 4 :(得分:7)

python词典中有一个方法可以执行此操作:dict.setdefault

connectionDetails.setdefault('host',someDefaultValue)
host = connectionDetails['host']

但是,如果尚未定义键connectionDetails['host'],则此方法会将someDefaultValue的值设置为host,与问题不同。

答案 5 :(得分: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'

答案 6 :(得分:2)

测试@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:\n a=d[1]\nexcept KeyError:\n a=10")
0.011889292989508249
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="try:\n a=d[2]\nexcept KeyError:\n 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:\n a=d[1]\nelse:\n a=10")
0.011475925013655797
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="if 2 in d:\n a=d[2]\nelse:\n a=10")
0.009605801998986863
>>>> timeit.timeit(setup="d={1:2, 3:4, 5:6, 7:8, 9:0}",
.... stmt="if 2 in d:\n a=d[2]\nelse:\n a=d[1]")
0.017342638995614834

答案 7 :(得分:1)

您可以将lamba函数用作单行。创建一个新对象connectionDetails2,可以像函数一样访问...

connectionDetails2 = lambda k: connectionDetails[k] if k in connectionDetails.keys() else "DEFAULT"

现在使用

connectionDetails2(k)

而不是

connectionDetails[k]

如果键中有k则返回字典值,否则返回"DEFAULT"