티스토리 뷰

반응형

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

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

 

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

Access an arbitrary element in a dictionary in Python

Python의 딕셔너리에서 임의 요소 액세스

 문제 내용 

If a mydict is not empty, I access an arbitrary element as:

mydict가 비어 있지 않으면 다음과 같이 임의 요소에 액세스합니다.
mydict[mydict.keys()[0]]

 

Is there any better way to do this?

이것을 하는 더 좋은 방법이 없을까요?

 

 

 

 높은 점수를 받은 Solution 

On Python 3, non-destructively and iteratively:

파이썬 3에서 비파괴적(원본을 변화시키지 않는 함수)이고 반복적으로:
next(iter(mydict.values()))

 

On Python 2, non-destructively and iteratively:

파이썬 2에서 비파괴적(원본을 변화시키지 않는 함수)이고 반복적으로:
mydict.itervalues().next()

 

If you want it to work in both Python 2 and 3, you can use the six package:

Python 2와 3 모두에서 작동하게 하려면 six 패키지를 사용할 수 있습니다.
six.next(six.itervalues(mydict))

 

though at this point it is quite cryptic and I'd rather prefer your code.

이 시점에서 그것은 꽤나 암호화되어 있어 저는 당신의 코드를 선호합니다.

 

If you want to remove any item, do:

항목을 제거하려면 다음을 수행합니다.
key, value = mydict.popitem()

 

Note that "first" may not be an appropriate term here because dict is not an ordered type in Python < 3.6. Python 3.6+ dicts are ordered.

dict는 Python < 3.6에서 정렬된 유형이 아니기 때문에 여기서 "first"는 적절한 용어가 아닐 수 있습니다. Python 3.6+ dicts는 입력 순서를 보존합니다.

 

 

 

 가장 최근 달린 Solution 

to get a key

키 가져오기
next(iter(mydict))

 

to get a value

값 가져오기
next(iter(mydict.values()))

 

to get both

둘 다 얻기
next(iter(mydict.items())) # or next(iter(mydict.viewitems())) in python 2

 

The first two are Python 2 and 3. The last two are lazy in Python 3, but not in Python 2.

첫 번째 두 개는 파이썬 2와 3입니다. 마지막 두 개는 파이썬 3에서는 게으르지만 파이썬 2에서는 그렇지 않습니다.

 

 

 

출처 : https://stackoverflow.com/questions/3097866/access-an-arbitrary-element-in-a-dictionary-in-python

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