Programming

사전 및 기본값

procodes 2020. 5. 14. 20:53
반응형

사전 및 기본값


connectionDetails파이썬 사전 이라고 가정하면 , 이와 같은 코드를 리팩토링하는 가장 훌륭하고 가장 우아하고 "파이 토닉 한"방법은 무엇입니까?

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

이처럼 :

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

다음 defaultdict과 같이 사용할 수도 있습니다 .

from collections import defaultdict
a = defaultdict(lambda: "default", key="some_value")
a["blabla"] => "default"
a["key"] => "some_value"

람다 대신 일반 함수를 전달할 수 있습니다.

from collections import defaultdict
def a():
  return 4

b = defaultdict(a, key="some_value")
b['absent'] => 4
b['key'] => "some_value"

하지만 .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

여러 다른 기본값의 경우 다음을 시도하십시오.

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

파이썬 사전에는 다음과 같은 방법이 있습니다. dict.setdefault

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

그러나이 방법 은 질문과 달리 가 아직 정의되지 않은 경우 값을 connectionDetails['host']설정합니다 .someDefaultValuehost


(이것은 늦은 대답입니다)

대안은 클래스를 서브 클래 싱하고 다음 dict과 같이 __missing__()메소드를 구현하는 것입니다.

class ConnectionDetails(dict):
    def __missing__(self, key):
        if key == 'host':
            return "localhost"
        raise KeyError(key)

Examples:

>>> 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'

Testing @Tim Pietzcker's suspicion about the situation in PyPy (5.2.0-alpha0) for Python 3.3.5, I find that indeed both .get() and the if/else way perform similar. Actually it seems that in the if/else case there is even only a single lookup if the condition and the assignment involve the same key (compare with the last case where there is two lookups).

>>>> 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

You can use a lamba function for this as a one-liner. Make a new object connectionDetails2 which is accessed like a function...

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

Now use

connectionDetails2(k)

instead of

connectionDetails[k]

which returns the dictionary value if k is in the keys, otherwise it returns "DEFAULT"

참고URL : https://stackoverflow.com/questions/9358983/dictionaries-and-default-values

반응형