Get first N key:value pairs of a dictionary in Python
Hello programmers, in this tutorial, we will learn how to get first N key:value pairs of a dictionary in Python.
we have a dictionary with keys and values
d={‘a’:1,’b’:2,’c’:3,’d’:4,’e’:5}
We want to get the first three keys and values from this dictionary: {‘a’:1,’b’:2,’c’:3}.
coding
- First, we create a dictionary, and then we will get their items using the items() method, which will return the key-value pair in the list.
- Then using the same items() method, we will extract the first N items of the list and convert these key-values pairs we will convert them into dictionaries using the
dict()
method.
#dictionary d={'a':1,'b':2,'c':3,'d':4,'e':5} # printing original dictionary print("The original dictionary : ",d) #items() method print("iteams: ",d.items()) # first N keys-values N = 3 # Get first N keys-items in dictionary d1= dict(list(d.items())[0: N]) # printing result print("Dictionary of first keys and values : ",d1)
output:
The original dictionary : {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5} iteams: dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]) Dictionary of first keys and values : {'a': 1, 'b': 2, 'c': 3}
Hopefully, you have learned how to get first N key: value pairs of a dictionary in Python.
Also, read: Python dictionary setdefault() method
Leave a Reply