深度阅读

How to get the last N key-value pairs in a Python dictionary?

作者
作者
2023年08月22日
更新时间
9.54 分钟
阅读时间
0
阅读量

To get the last N key-value pairs of a Python dictionary, you can use the list() function to convert the dictionary items to a list, and then use list slicing to get the last N items. Here’s an example:

my_dict = {'A': 3, 'B': 4, 'C': 1, 'D': 2, 'E': 5}

n = 3

last_n_items = dict(list(my_dict.items())[-n:])

print(last_n_items)

This will output the last three key-value pairs of the dictionary:

{'C': 1, 'D': 2, 'E': 5}

Note that the slicing operation returns a list of tuples (key-value pairs), so we need to convert the result back to a dictionary using the dict() function.

If you want to get the last N items without creating a new dictionary, you can just iterate over the sliced items:

my_dict = {'A': 3, 'B': 4, 'C': 1, 'D': 2, 'E': 5}

n = 3

for key, value in list(my_dict.items())[-n:]:
    print(key, value)

This will output the last three key-value pairs of the dictionary:

C 1
D 2
E 5

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。