개발/파이썬

키가 Dictionary에 이미 있는지 확인하는 방법

맨날치킨 2022. 11. 30. 21:05
반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Check if a given key already exists in a dictionary

Key가 Dictionary에 이미 있는지 확인하는 방법

 문제 내용 

I wanted to test if a key exists in a dictionary before updating the value for the key. I wrote the following code:

키 값을 업데이트하기 전에 Dictionary에 키가 있는지 테스트하고 싶었습니다. 나는 다음 코드를 작성했다:

 

if 'key1' in dict.keys():
  print "blah"
else:
  print "boo"

I think this is not the best way to accomplish this task. Is there a better way to test for a key in the dictionary?

나는 이것이 이 일을 수행하는 최선의 방법이 아니라고 생각한다. 사전에서 키를 테스트하는 더 좋은 방법이 있나요?

 

 

 

 높은 점수를 받은 Solution 

in tests for the existence of a key in a dict:

Dictionary에 키가 있는지 테스트할 때:
d = {"key1": 10, "key2": 23}

if "key1" in d:
    print("this will execute")

if "nonexistent key" in d:
    print("this will not")

Use dict.get() to provide a default value when the key does not exist:

키가 없을 때 dict.get()을 사용하여 기본값을 제공합니다.

 

d = {}

for i in range(10):
    d[i] = d.get(i, 0) + 1

To provide a default value for every key, either use dict.setdefault() on each assignment:

모든 키에 기본값을 제공하려면 각 할당에 대해 dict.setdefault()를 사용합니다:
d = {}

for i in range(10):
    d[i] = d.setdefault(i, 0) + 1

 

or use defaultdict from the collections module:

또는 컬렉션 모듈의 defaultdict를 사용합니다.
from collections import defaultdict

d = defaultdict(int)

for i in range(10):
    d[i] += 1

 

 

 가장 최근 달린 Solution 

Check if a given key already exists in a dictionary

키가 Dictionary에 이미 있는지 확인

 

To get the idea how to do that we first inspect what methods we can call on dictionary.

어떻게 해야 하는지 아이디어를 얻기 위해 먼저 Dictionary에서 어떤 방법을 호출할 수 있는지 검사합니다.

 

Here are the methods:

방법은 다음과 같습니다.

 

d={'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}

Python Dictionary clear()        Removes all Items
Python Dictionary copy()         Returns Shallow Copy of a Dictionary
Python Dictionary fromkeys()     Creates dictionary from given sequence
Python Dictionary get()          Returns Value of The Key
Python Dictionary items()        Returns view of dictionary (key, value) pair
Python Dictionary keys()         Returns View Object of All Keys
Python Dictionary pop()          Removes and returns element having given key
Python Dictionary popitem()      Returns & Removes Element From Dictionary
Python Dictionary setdefault()   Inserts Key With a Value if Key is not Present
Python Dictionary update()       Updates the Dictionary
Python Dictionary values()       Returns view of all values in dictionary

The brutal method to check if the key already exists may be the get() method:

키가 이미 존재하는지 확인하는 확실한 방법은 get() 방법일 수 있습니다.
d.get("key")

 

The other two interesting methods items() and keys() sounds like too much of work. So let's examine if get() is the right method for us. We have our dict d:

다른 두 가지 흥미로운 방법 items()와 keys()는 너무 많은 작업으로 들린다. 그래서 get()이 우리에게 맞는 방법인지 검토해 보자. 우리는 dictionary d를 가지고 있다.
d= {'clear':0, 'copy':1, 'fromkeys':2, 'get':3, 'items':4, 'keys':5, 'pop':6, 'popitem':7, 'setdefault':8, 'update':9, 'values':10}

 

Printing shows the key we don't have will return None:

프린팅은 키가 없을 때 None을 반환하는 것을 보여줍니다.
print(d.get('key')) #None
print(d.get('clear')) #0
print(d.get('copy')) #1

 

We use that to get the information if the key is present or no. But consider this if we create a dict with a single key:None:

우리는 키가 있는지 없는지에 대한 정보를 얻기 위해 그것을 사용한다. 그러나 단일 키를 사용하여 딕트를 생성하는 경우 다음을 고려하십시오. Key:None :
d= {'key':None}
print(d.get('key')) #None
print(d.get('key2')) #None

 

Leading that get() method is not reliable in case some values may be None.

일부 값이 없음일 경우 get() 메서드를 선행하는 것은 신뢰할 수 없습니다.

 

This story should have a happier ending. If we use the in comparator:

이 이야기는 더 행복한 결말을 맺어야 한다. in 비교기를 사용하는 경우:
print('key' in d) #True
print('key2' in d) #False

 

We get the correct results.

우리는 정확한 결과를 얻는다.

 

We may examine the Python byte code:

파이썬 바이트 코드는 다음과 같다:
import dis
dis.dis("'key' in d")
#   1           0 LOAD_CONST               0 ('key')
#               2 LOAD_NAME                0 (d)
#               4 COMPARE_OP               6 (in)
#               6 RETURN_VALUE

dis.dis("d.get('key2')")
#   1           0 LOAD_NAME                0 (d)
#               2 LOAD_METHOD              1 (get)
#               4 LOAD_CONST               0 ('key2')
#               6 CALL_METHOD              1
#               8 RETURN_VALUE

 

This shows that in compare operator is not just more reliable, but even faster than get().

이것은 비교 연산자가 get()보다 더 신뢰할 수 있을 뿐만 아니라 심지어 더 빠르다는 것을 보여준다.

 

 

 

출처 : https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary

반응형