Computer >> 컴퓨터 >  >> 프로그램 작성 >> Python

Python의 사전에서 최대값으로 키 가져오기

<시간/>

Python 사전에는 키 값 쌍이 포함되어 있습니다. 이 기사에서는 주어진 파이썬 사전에서 값이 최대인 요소의 키를 얻는 방법을 볼 것입니다.

최대 및 get

get 함수와 max 함수를 사용하여 키를 가져옵니다.

dictA = {"Mon": 3, "Tue": 11, "Wed": 8}
print("Given Dictionary:\n",dictA)
# Using max and get
MaxKey = max(dictA, key=dictA.get)
print("The Key with max value:\n",MaxKey)

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given Dictionary:
{'Mon': 3, 'Tue': 11, 'Wed': 8}
The Key with max value:
Tue

itemgetter 및 max 사용

itemgetter 함수를 사용하여 사전의 항목을 가져오고 위치를 1로 인덱싱하여 값을 얻습니다. 다음으로 왜 max 함수를 적용하고 마지막으로 필요한 키를 얻습니다.

import operator
dictA = {"Mon": 3, "Tue": 11, "Wed": 8}
print("Given Dictionary:\n",dictA)
# Using max and get
MaxKey = max(dictA.items(), key = operator.itemgetter(1))[0]
print("The Key with max value:\n",MaxKey)

출력

위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -

Given Dictionary:
{'Mon': 3, 'Tue': 11, 'Wed': 8}
The Key with max value:
Tue