4
3

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 5 years have passed since last update.

Pythonの辞書型で複数の最大値のkeyを取得する

Last updated at Posted at 2017-07-21

やりたいこと

valueの最大値が複数ある辞書

d = {
  'a': 1,
  'b': 2,
  'c': 3,
  'd': 3,
  'e': 2
}

に対して,複数のkey(今回だと[c, d])を取得する処理をしたい

実装(2017/7/24追記)

@shiracamus 様より

numpy使わない方がシンプルでは?

by_shiracamus.py
d = {
  'a': 1,
  'b': 2,
  'c': 3,
  'd': 3,
  'e': 2
}

# valueがmaxであるkeyを探してくる
max_val = max(d.values())
keys_of_max_val = [key for key in d if d[key] == max_val]

print(keys_of_max_val)

きれい!
keys_of_max_val = [key for key, val in d.items() if val == max_val]とかにすると見た目が好みだけれど,速度ってどうなるんだっけか…
暇な時にでも調べよう…

前のやつ

import numpy as np

d = {
  'a': 1,
  'b': 2,
  'c': 3,
  'd': 3,
  'e': 2
}

# keyをndarrayで取得
keys = np.array([a[0] for a in d.items()])

# valueをndarrayで取得
values = np.array([a[1] for a in d.items()])

# valueがmaxであるkeyを探してくる
keys_of_max_val = keys[values == values.max()]

print(keys_of_max_val)

内包表記に慣れていないのバレバレですねぇ!

できた

['c' 'd']

感想

最大値が1つしかないときは

key_of_max_val = max(d.items(), key=(lambda x: x[1]))[0]

で取得できるのに,たくさん最大値があると途端に面倒くさくなるなー

4
3
2

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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?