티스토리 뷰

반응형

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

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

 

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

How do you find the first key in a dictionary?

딕셔너리에서 첫 번째 키를 찾는 방법은 무엇인가요?

 문제 내용 

I am trying to get my program to print out "banana" from the dictionary. What would be the simplest way to do this?

프로그램에서 딕셔너리의 "banana"를 출력하려고 합니다. 가장 간단한 방법은 무엇일까요?

 

This is my dictionary:

다음은 제 딕셔너리입니다:
prices = {
    "banana" : 4,
    "apple" : 2,
    "orange" : 1.5,
    "pear" : 3
}

 

 

 높은 점수를 받은 Solution 

On a Python version where dicts actually are ordered, you can do

실제로 dict가 순서대로 정렬된 Python 버전에서는 다음과 같이 할 수 있습니다.
my_dict = {'foo': 'bar', 'spam': 'eggs'}
next(iter(my_dict)) # outputs 'foo'

 

For dicts to be ordered, you need Python 3.7+, or 3.6+ if you're okay with relying on the technically-an-implementation-detail ordered nature of dicts on CPython 3.6.

dict가 순서대로 정렬되려면 Python 3.7 이상이 필요합니다. CPython 3.6에서의 dict의 정렬 순서가 기술적으로 구현 세부 사항임에도 불구하고 3.6 이상인 경우에는 괜찮습니다.

 

For earlier Python versions, there is no "first key", but this will give you "a key", especially useful if there is only one.

이전 Python 버전의 경우 "첫 번째 키"는 없지만, "키"를 얻을 수 있습니다. 키가 하나만 있는 경우 특히 유용합니다.

 

 

 

 가장 최근 달린 Solution 

Assuming you want to print the first key:

첫 번째 키를 출력하려면 다음과 같이 합니다:
print(list(prices.keys())[0])

 

If you want to print first key's value:

첫 번째 키의 값을 출력하려면 다음과 같이 합니다:
print(prices[list(prices.keys())[0]])

 

 

출처 : https://stackoverflow.com/questions/30362391/how-do-you-find-the-first-key-in-a-dictionary

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