LoginSignup
0
1

More than 5 years have passed since last update.

Python 辞書を多次元リストにして並び替える

Posted at

この記事について

わたしは今、UdemyなどでPythonを学習しています。しかしどんどん忘れてしまうので、備忘録としてQiitaに記事として残します。

辞書をリストにする

辞書とは

Pythonにおける辞書(ディクショナリ)とは、大量のデータを効率的に扱う仕組みです。
ただし、リストと異なり数値であるインデックスを持ちません。その代わりに、Keyをもって、そのKeyごとにValueをもつ、という構造になっています。

例えば次のような感じです。

dict = {
    '東京': 600,
    '大阪': 800,
    '福岡': 700
}

東京、大阪、福岡がKeyで、600, 800, 700がそれぞれのKeyのValueです。
Keyで識別していますからKeyは重複不可ですので注意してください。

辞書の値を取り出すときは、

dict['東京']

のようにします。

では実際のコードを

def sell(place, sales):
    print(place, 'で', sales, '販売されました')

dict = {
    '東京': 600,
    '大阪': 800,
    '福岡': 700
}

items = list(dict.items())
sorted_items = sorted(items, key=lambda x: x[1], reverse=True)

print('元の順序', items)
print('大きい順', sorted_items)

l = len(items)-1
i = 0

while i <= l:
    sell(sorted_items[i][0], sorted_items[i][1])
    i += 1

いくばくかの解説

items = list(dict.items())

↑リスト型に変換します。
辞書はそのままだとソートできないので、ここで辞書型にしています。

print(type(items))

↑とすると、itemsがリスト型であることを確認できます。

list()

↑は組み込み関数で、カッコ内で与えられたものをリストに変換します。

sorted_items = sorted(items, key=lambda x: x[1], reverse=True)

↑並び替えています。reverse=Trueは、降順の場合です。何もなければ昇順です。
lambdaは、おいおい開設する機会を作ります。
ちょっと難しいのでここでは省略。すいません。

最後に

あくまでも個人的なメモですので、ご参考程度にお願いします。

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