티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to initialize a dict with keys from a list and empty value in Python?
Python 리스트에서 키를 가져와서 빈 값으로 딕셔너리를 초기화하려면 어떻게 해야 할까요?
문제 내용
I'd like to get from this:
나는 이것으로부터 얻고 싶다:
keys = [1,2,3]
to this:
이렇게 만들고 싶습니다.
{1: None, 2: None, 3: None}
Is there a pythonic way of doing it?
이 작업을 하는 파이썬답게 하는 방법이 있을까요?
This is an ugly way to do it:
이런 방법은 별로 예쁘지 않습니다.
>>> keys = [1,2,3]
>>> dict([(1,2)])
{1: 2}
>>> dict(zip(keys, [None]*len(keys)))
{1: None, 2: None, 3: None}
높은 점수를 받은 Solution
dict.fromkeys
directly solves the problem:
dict.fromkeys를 사용하면 문제가 해결됩니다.
>>> dict.fromkeys([1, 2, 3, 4])
{1: None, 2: None, 3: None, 4: None}
This is actually a classmethod, so it works for dict-subclasses (like collections.defaultdict
) as well.
이는 사실 dict의 클래스 메소드이므로 collections.defaultdict와 같은 dict 서브 클래스에 대해서도 작동합니다.
The optional second argument, which defaults to None
, specifies the value to use for the keys. Note that the same object will be used for each key, which can cause problems with mutable values:
두 번째 인자는 None으로 기본 설정되며 키에 대한 값을 지정합니다. 각 키에 대해 동일한 객체가 사용될 것이므로 변경 가능한 값으로 인해 문제가 발생할 수 있습니다.
>>> x = dict.fromkeys([1, 2, 3, 4], [])
>>> x[1].append('test')
>>> x
{1: ['test'], 2: ['test'], 3: ['test'], 4: ['test']}
If this is unacceptable, see How can I initialize a dictionary whose values are distinct empty lists? for a workaround.
이것이 허용되지 않으면 값이 비어있는 목록으로 초기화된 딕셔너리를 만드는 방법에 대해서는 How can I initialize a dictionary whose values are distinct empty lists?를 참조하세요.
가장 최근 달린 Solution
In many workflows where you want to attach a default / initial value for arbitrary keys, you don't need to hash each key individually ahead of time. You can use collections.defaultdict
. For example:
임의의 키에 대해 기본/초기 값을 연결하려는 많은 워크플로우에서는 미리 각 키를 해시할 필요가 없습니다. collections.defaultdict를 사용할 수 있습니다. 예를 들어:
from collections import defaultdict
d = defaultdict(lambda: None)
print(d[1]) # None
print(d[2]) # None
print(d[3]) # None
This is more efficient, it saves having to hash all your keys at instantiation. Moreover, defaultdict
is a subclass of dict
, so there's usually no need to convert back to a regular dictionary.
이렇게 하면 초기화할 때 모든 키를 해싱하지 않아도 되므로 더 효율적입니다. 또한 defaultdict는 dict의 서브 클래스이므로 일반 딕셔너리로 다시 변환할 필요가 거의 없습니다.
For workflows where you require controls on permissible keys, you can use dict.fromkeys
as per the accepted answer:
허용 가능한 키에 대한 제어가 필요한 경우에는 accepted answer와 같이 dict.fromkeys를 사용할 수 있습니다.
d = dict.fromkeys([1, 2, 3, 4])
출처 : https://stackoverflow.com/questions/2241891/how-to-initialize-a-dict-with-keys-from-a-list-and-empty-value-in-python
'개발 > 파이썬' 카테고리의 다른 글
데이터 프레임에 빈 열을 추가하는 방법 (0) | 2023.02.17 |
---|---|
튜플 리스트에서 특정 아이템 기준으로 정렬하기 (0) | 2023.02.16 |
딕셔너리의 모든 값들의 합을 구하는 방법 (0) | 2023.02.15 |
판다스(Pandas) 데이터프레임(DataFrame)을 딕셔너리의 리스트로 변환하기 (0) | 2023.02.15 |
중첩(다중) 리스트를 1차원 리스트로 만들기 (0) | 2023.02.15 |