6
4

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 値に優先順位をつけてキーをソートする方法

Last updated at Posted at 2018-10-24

###第一要素で昇順にソート後、同じ値を持つキーを第二要素で降順にソート

test.py

dct = {
	'apple': (1,20),
	'banana': (5,40),
	'melon': (3,60),
	'potato': (3,20),
	'carrot': (5,80)
	}


dct_sorted = sorted(dct.items(), key=lambda x: (x[1][0], -x[1][1]))

print(dct_sorted)

#結果

[('apple', (1, 20)), ('melon', (3, 60)), ('potato', (3, 20)), ('carrot', (5, 80)), ('banana', (5, 40))]


6
4
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?