티스토리 뷰

반응형

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

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

 

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

Filter dict to contain only certain keys?

특정 키만 포함하도록 딕셔너리를 필터링하시겠습니까?

 문제 내용 

I've got a dict that has a whole bunch of entries. I'm only interested in a select few of them. Is there an easy way to prune all the other ones out?

저는 많은 아이템이 있는 딕셔너리를 가지고 있습니다. 저는 그들 중 엄선된 몇 개에만 관심이 있습니다. 다른 것들을 모두 쳐낼 수 있는 쉬운 방법이 있나요?

 

 

 

 높은 점수를 받은 Solution 

Constructing a new dict:

새 딕셔너리 구성:
dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys }

 

Uses dictionary comprehension.

사전 내포 사용하기

 

If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((your_key, old_dict[your_key]) for ...). It's the same, though uglier.

이들이 없는 버전(예: Python 2.6 및 이전 버전)을 사용하는 경우 ...에 대해 dict(your_key, old_dict[your_key])로 만듭니다. 더 못생겼지만 똑같습니다.

 

Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dicts of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.

이것은 jnnnnn의 버전과 달리 모든 크기의 old_dicts에 대해 안정적인 성능(your_keys의 수에만 의존함)을 갖는다는 점에 유의하십시오. 속도와 메모리 측면에서 모두. 이는 생성기 표현식이므로 한 번에 하나의 항목을 처리하고 old_dict의 모든 항목을 살펴보지는 않습니다.

 

Removing everything in-place:

원래 데이터에서 모든 항목 제거:
unwanted = set(keys) - set(your_dict)
for unwanted_key in unwanted: del your_dict[unwanted_key]

 

 

 가장 최근 달린 Solution 

If you know the negation set (aka not keys) in advance:

사전에 제외 할 키를 알고 있는 경우:
v = {'a': 'foo', 'b': 'bar', 'command': 'fizz', 'host': 'buzz'  }
args = {k: v[k] for k in v if k not in ["a", "b"]}
args # {'command': 'fizz', 'host': 'buzz'}

 

 

출처 : https://stackoverflow.com/questions/3420122/filter-dict-to-contain-only-certain-keys

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