Development/Python
[Python] Dictionary의 Value를 얻을 때, 존재하지 않는 Key는 넘어가야 하는 경우(KeyError 해결)
성딱이
2022. 2. 9. 18:01
반응형
Dictionary를 사용해서 Value를 얻고자 할 때, Dictionary에 존재하지 않는 Key를 입력하면 KeyError가 발생한다.
이 때, Default Value를 지정해 줘서 Key가 존재하는 것에 대해서만 Value를 얻고 넘어갈 수 있는 방법을 소개한다.
방법
dictionary.get(key, 'Default Value')
예시
In [79]:
example_dict = {
'A' : '-ETF'
, 'B' : '-FUND'
, 'C' : '-STOCK'
}
In [1]:
example_dict.get('A', 'if not')
Out[1]:
'-ETF'
In [2]:
example_dict.get('D', 'if not')
Out[2]:
'if not'
Default Value를 조회하고자 하는 Key를 그대로 입력해줘도 상관 없다.
ex = 'DF'
In [3]:
example_dict.get(ex, ex)
Out[2]:
'DF'
출처 : https://stackoverflow.com/questions/6130768/return-none-if-dictionary-key-is-not-available
Return None if Dictionary key is not available
I need a way to get a dictionary value if its key exists, or simply return None, if it does not. However, Python raises a KeyError exception if you search for a key that does not exist. I know tha...
stackoverflow.com
반응형