1
1

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のdict型をkey, valueの両方でソートする

Last updated at Posted at 2017-03-28

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

まとめ

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

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

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

私の書いたのは、

.py
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でソートするというコードを書きました

```.py
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を利用して以下のように記載し無事解決しました

```.py
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?