티스토리 뷰

반응형

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

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

 

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

Check if a given key already exists in a dictionary and increment it

주어진 딕셔너리에서 키가 이미 존재하는지 확인하고 값을 증가시키려면 어떻게해야 합니까?

 문제 내용 

How do I find out if a key in a dictionary has already been set to a non-None value?

어떤 딕셔너리의 키가 이미 값이 None이 아닌 값으로 설정되어 있는지 어떻게 알 수 있을까요?

 

I want to increment the value if there's already one there, or set it to 1 otherwise:

만약 그렇다면 값을 증가시키고, 그렇지 않으면 1로 설정하고 싶습니다.
my_dict = {}

if my_dict[key] is not None:
  my_dict[key] = 1
else:
  my_dict[key] += 1

 

 

 높은 점수를 받은 Solution 

You are looking for collections.defaultdict (available for Python 2.5+). This

이러한 경우 collections.defaultdict (Python 2.5+에서 사용 가능)를 사용해야 합니다.
from collections import defaultdict

my_dict = defaultdict(int)
my_dict[key] += 1

 

will do what you want.

이는 원하는 작업을 수행할 수 있습니다.

 

For regular Python dicts, if there is no value for a given key, you will not get None when accessing the dict -- a KeyError will be raised. So if you want to use a regular dict, instead of your code you would use

일반적인 Python 딕셔너리에 대해서는, 주어진 키에 대한 값이 없는 경우, 딕셔너리에 액세스 할 때 None이 반환되지 않습니다. 대신 KeyError가 발생합니다. 그래서 정규의 딕셔너리를 사용하려면, 당신이 코드를 사용하는 대신에 아래 코드를 사용하세요.
if key in my_dict:
    my_dict[key] += 1
else:
    my_dict[key] = 1

 

 

 가장 최근 달린 Solution 

This isn't directly answering the question, but to me, it looks like you might want the functionality of collections.Counter.

질문에 직접 대답하는 것은 아니지만, collections.Counter의 기능이 필요할 것 같습니다.
from collections import Counter

to_count = ["foo", "foo", "bar", "baz", "foo", "bar"]

count = Counter(to_count)

print(count)

print("acts just like the desired dictionary:")
print("bar occurs {} times".format(count["bar"]))

print("any item that does not occur in the list is set to 0:")
print("dog occurs {} times".format(count["dog"]))

print("can iterate over items from most frequent to least:")
for item, times in count.most_common():
    print("{} occurs {} times".format(item, times))

 

This results in the output

결과는 다음과 같습니다.
Counter({'foo': 3, 'bar': 2, 'baz': 1})
acts just like the desired dictionary:
bar occurs 2 times
any item that does not occur in the list is set to 0:
dog occurs 0 times
can iterate over items from most frequent to least:
foo occurs 3 times
bar occurs 2 times
baz occurs 1 times

 

 

출처 : https://stackoverflow.com/questions/473099/check-if-a-given-key-already-exists-in-a-dictionary-and-increment-it

반응형
댓글
공지사항
최근에 올라온 글