LoginSignup
1
1

More than 5 years have passed since last update.

Pythonのdict型をkey, valueの両方でソートする

Last updated at Posted at 2017-03-28

Python3のdict型を使っていて、keyとvalueの両方でソートする必要がありました。

まとめ

まず、コメントでおしえていただきました望ましい書き方を提示します。これを含むコメントに記載いただいた方法がベストかと思います。

sorted_last_record = sorted(last_record.items(), key=lambda x: (x[1], x[0]))

※詳しくはコメントを御参照ください。

私の書いたのは、

from collections import OrderedDict
sorted_last_record = OrderedDict(sorted(last_record.items(), key=lambda x: x[0]))
sorted_last_record = sorted(sorted_last_record.items(), key=lambda x: x[1])

でした。あまり意味がなさそうですが、たとえば、keyは昇順、valueは降順であるときとか、ソートする条件がkeyとvalueで違うときには、それなりに意味があったりしないですかね?

内容

最初、

dictをkeyでソートして、その後、valueでソートする、というコードを書きました。

sorted_last_record = sorted(last_record.items(), key=lambda x: x[0])
sorted_last_record = sorted(dict(sorted_last_record).items(), key=lambda x: x[1])

しかし、これでは2行目で、dictに変換したところで、順番が維持されない問題にあたり、時に正解が得られ、時に不正解が得られる、という状況になりました。

そこで、OrderdDictを利用して以下のように記載し、無事解決しました。

from collections import OrderedDict
sorted_last_record = OrderedDict(sorted(last_record.items(), key=lambda x: x[0]))
sorted_last_record = sorted(sorted_last_record.items(), key=lambda x: x[1])

もっと賢い書き方があると思うので、おしえてもらえるとありがたいです。
よろしくお願いいたします。

1
1
3

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
1
1