티스토리 뷰

반응형

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

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

 

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

Get key by value in dictionary

딕셔너리에서 값으로 키 가져오기

 문제 내용 

I made a function which will look up ages in a Dictionary and show the matching name:

저는 딕셔너리에서 나이를 검색하고 일치하는 이름을 보여주는 기능을 만들었습니다:
dictionary = {'george' : 16, 'amber' : 19}
search_age = raw_input("Provide age")
for age in dictionary.values():
    if age == search_age:
        name = dictionary[age]
        print name

 

I know how to compare and find the age I just don't know how to show the name of the person. Additionally, I am getting a KeyError because of line 5. I know it's not correct but I can't figure out how to make it search backwards.

저는 나이를 비교하고 찾는 방법을 알고 있지만 그 사람의 이름을 어떻게 보여줘야 할지 모르겠습니다. 추가로 5번 라인 때문에 KeyError가 발생합니다. 저는 그것이 옳지 않다는 것을 알지만 어떻게 그것을 거꾸로 검색하게 하는지 모르겠습니다.

 

 

 

 높은 점수를 받은 Solution 

mydict = {'george': 16, 'amber': 19}
print mydict.keys()[mydict.values().index(16)]  # Prints george

 

Or in Python 3.x:

또는 Python 3.x에서:
mydict = {'george': 16, 'amber': 19}
print(list(mydict.keys())[list(mydict.values()).index(16)])  # Prints george

 

Basically, it separates the dictionary's values in a list, finds the position of the value you have, and gets the key at that position.

기본적으로 리스트에서 딕셔너리의 값을 구분하고 사용자가 가지고 있는 값의 위치를 찾은 다음 해당 위치에서 키를 가져옵니다.

 

More about keys() and .values() in Python 3: How can I get list of values from dict?

파이썬 3의 keys() 및 values()에 대한 자세한 내용: dict에서 값 목록을 가져오려면 어떻게 해야 합니까?

 

 

 

 가장 최근 달린 Solution 

One line solution using list comprehension, which returns multiple keys if the value is possibly present multiple times.

리스트 내포를 사용하는 한 줄 솔루션으로, 값이 여러 번 있을 경우 여러 키를 반환합니다.
[key for key,value in mydict.items() if value == 16]

 

 

출처 : https://stackoverflow.com/questions/8023306/get-key-by-value-in-dictionary

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