深度阅读

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

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

To get the first N key-value pairs of a Python dictionary, you can use dictionary slicing along with the list() function to convert the result back to a dictionary. Here’s an example:

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

n = 3

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

print(first_n_items)

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

{'A': 3, 'B': 4, 'C': 1}

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.

Alternatively, you can use a loop to iterate over the dictionary items and populate a new dictionary with the first N items:

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

n = 3

first_n_items = dict()

for i, (key, value) in enumerate(my_dict.items()):
    if i < n:
        first_n_items[key] = value
    else:
        break

print(first_n_items)

This will produce the same output as the previous example.

相关标签

博客作者

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