0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python Tips】辞書から最大値を持つkeyを複数取り出す方法

Last updated at Posted at 2020-02-16

ABC155 C - Pollで連想配列で解ける問題が出たが、表題の処理がうまく書けなかったのでメモ。

最大値を持つkeyは複数あることを想定しています。(2020/02/19更新)

dic_max.py
# 適当に辞書初期化
d = {}
d["k1"] = 10
d["k2"] = 20
print(d)
# {'k1': 10, 'k2': 20}
dic_max.py
# 辞書dのvalueの最大値を取り出す処理 -> max(d.values())
max_val = max(d.values())
print(d.values())
print(max(d.values()))
# dict_values([10, 20])
# 20

# これはエラー
# print(d.value[0])
# TypeError: 'dict_values' object does not support indexing
dic_max.py
# keyとvalueをfor文で回す前処理 -> d.items()
print(d.items())
# dict_items([('k1', 10), ('k2', 20)])

# これはエラー
# 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)])からループ一回目は
# kv = ('k1', 10)として取り出せる(kv[0] = 'k1'、kv[1] = 10)。
# kv[1] == max_valでvalue最大値と同じ値の時だけリストにkv[0](=key)追加
# 二回目以降も同様


# リストやタプルに*を付けて引数に指定 -> 展開されてそれぞれの要素が個別に渡される
print(*max_k_ls)
# k2

参考サイト

AtCoder Beginner Contest 155
Pythonで辞書の値の最大値・最小値とそのキーを取得

追記

コメントでアドバイス頂いた手法
@shiracamus さん
@konandoiruasa さん
@nkay さん
ありがとうございます。

・keyの最大値に被りが無い場合

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

・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']
0
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?