[Python Tips] How to retrieve multiple keys with the maximum value from the dictionary

ABC155 C --Poller had a problem that could be solved with an associative array, but I couldn't write the title well, so I made a note.

It is assumed that there are multiple keys with the maximum value. (Updated on February 19, 2020)

dic_max.py


#Appropriate dictionary initialization
d = {}
d["k1"] = 10
d["k2"] = 20
print(d)
# {'k1': 10, 'k2': 20}

dic_max.py


#Processing to retrieve the maximum value of the dictionary d-> max(d.values())
max_val = max(d.values())
print(d.values())
print(max(d.values()))
# dict_values([10, 20])
# 20

#This is an error
# print(d.value[0])
# TypeError: 'dict_values' object does not support indexing

dic_max.py


#Pre-processing to turn key and value with for statement-> d.items()
print(d.items())
# dict_items([('k1', 10), ('k2', 20)])

#This is an error
# print(d_i[0])
# TypeError: 'dict_items' object does not support indexing

dic_max.py


max_k_ls = [kv[0] for kv in d.items() if kv[1]==max_val]
# d.items() = dict_items([('k1', 10), ('k2', 20)])From the first loop
# kv = ('k1', 10)Can be taken out as(kv[0] = 'k1'、kv[1] = 10)。
# kv[1] == max_Only when val has the same value as the maximum value, kv is added to the list.[0](=key)add to
#Same for the second and subsequent times


#For lists and tuples*Specify as an argument with->Expanded and each element is passed individually
print(*max_k_ls)
# k2

Reference site

AtCoder Beginner Contest 155 Get the maximum / minimum value of the dictionary and its key in Python

Postscript

Method advised in the comments @shiracamus @konandoiruasa @nkay Thank you very much.

・ When the maximum value of key is not covered

>>> d = {"k1": 10, "k2": 20}
>>> d
{'k1': 10, 'k2': 20}
>>> max(d, key=lambda k: d[k])
'k2'

・ Method using pandas

>>> import pandas as pd
>>> import numpy as np
>>> d = {"k1": 10, "k2": 20, "k3": 20}
>>> df = pd.DataFrame([d])
>>> list(df.columns[np.where(df.iloc[0] == df.iloc[0].max())])
['k2', 'k3']

Recommended Posts

[Python Tips] How to retrieve multiple keys with the maximum value from the dictionary
How to retrieve the nth largest value in Python
[Python] How to draw multiple graphs with Matplotlib
Get multiple maximum keys in Python dictionary type
[Python] How to remove duplicate values from the list
How to scrape image data from flickr with python
[Introduction to Python] How to iterate with the range function?
[Python] How to specify the download location with youtube-dl
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary
How to retrieve multiple arrays using slice in python.
[Python] How to rewrite the table style with python-pptx [python-pptx]
Get the value of a specific key in a list from the dictionary type in the list with Python
I tried to simulate how the infection spreads with Python
[python] How to check if the Key exists in the dictionary
How to slice a block multiple array from a multiple array in Python
How to convert an array to a dictionary with Python [Application]
[python] Summary of how to retrieve lists and dictionary elements
How to get the last (last) value in a list in Python
How to get all the keys and values in the dictionary
How to get into the python development environment with Vagrant
[Introduction to Python] How to get data with the listdir function
Extract the value closest to a value from a Python list element
How to scrape stock prices of individual stocks from the Nikkei newspaper website with Python
How to check if the contents of the dictionary are the same in Python by hash value
How to know the number of GPUs from python ~ Notes on using multiprocessing with pytorch ~
Python: How to use async with
Extract the maximum value with pandas.
Replace dictionary value with Python> update ()
Create folders from '01' to '12' with python
How to get the Python version
How to get started with Python
[Python] How to import the library
How to use FTP with Python
How to calculate date with python
How to access wikipedia from python
How to get followers and followers from python using the Mastodon API
How to check the memory size of a dictionary in Python
Tips: [Python] Calculate the average value of the specified area with bedgraph
From the introduction of JUMAN ++ to morphological analysis of Japanese with Python
How to send a request to the DMM (FANZA) API with python
How to deal with the problem that the current directory moves when Python is executed from Atom
Find the maximum value python (fixed ver)
The 16th offline real-time how to write problem was solved with Python
How to title multiple figures with matplotlib
[Python] What is a formal argument? How to set the initial value
How to crop the lower right part of the image with Python OpenCV
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
How to update Google Sheets from Python
How to deal with OAuth2 error when using Google APIs from Python
How to get the date and time difference in seconds with python
How to utilize multi-core from multiple languages
How to work with BigQuery in Python
[Introduction to Python] How to sort the contents of a list efficiently with list sort
How to get a value from a parameter store in lambda (using python)
Use numpy's .flatten () [0] to retrieve the value
How to do portmanteau test with python
How to display python Japanese with lolipop
How to access RDS from Lambda (python)
How to operate Linux from the console
[Python] How to use list 2 Reference of list value, number of elements, maximum value, minimum value
[Python] How to set the (client) window size inside the browser with Selenium