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
AtCoder Beginner Contest 155 Get the maximum / minimum value of the dictionary and its key in Python
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']