2024年9月23日月曜日

how to show first 5 of python dictionary

 Python

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}

# Method 1: Using list comprehension
first_5_items = [(key, value) for key, value in my_dict.items()][:5]
print(first_5_items)

# Method 2: Using itertools.islice
import itertools
first_5_items = dict(itertools.islice(my_dict.items(), 5))
print(first_5_items)

Both methods will output the first 5 key-value pairs from the dictionary:

[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]

0 件のコメント:

コメントを投稿