0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python 辞書の後ろからn個分を順番に処理する方法

Posted at

結論

辞書 sample_dic の後ろ n 個分を前から順番に処理する場合

dict(list(sample_dic.items())[-n:])

説明

辞書ではスライスを使えないので、一旦、リストに変換しスライスを使って後ろn個を取り出す。それを再度、辞書に変換する。

補足

辞書に順番があるのは Python 3.7 以降。

サンプル

sample_dic = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8}

for k,v in  dict(list(sample_dic.items())[-3:]).items() :
  print(k,v)

実行結果

f 6
g 7
h 8
0
0
1

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?