Print specific key-value pairs of a dictionary in Python

avatar

Borislav Hadzhiev

Last updated: Sep 17, 2022

banner

Photo from Unsplash

Print specific key-value pairs of a dictionary in Python #

To print specific key-value pairs of a dictionary:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use a for loop to iterate over the view.
  3. Check if each value meets a condition.
  4. Use the print() function to print the matching key-value pairs.
main.py
my_dict = { 'name': 'Borislav Hadzhiev', 'fruit': 'apple', 'number': 5, 'website': 'bobbyhadz.com', 'topic': 'Python' } # ✅ Print key-value pairs of dict that meet a condition for key, value in my_dict.items(): if str(value).startswith('bo'): print(key, value) # 👉️ website bobbyhadz.com # -------------------------------------------------- # ✅ print first N key-value pairs of dict firstN = list(my_dict.items())[:3] # 👇️ [('name', 'Borislav Hadzhiev'), ('fruit', 'apple'), ('number', 5)] print(firstN) for key, value in firstN: # name Borislav Hadzhiev # fruit apple # number 5 print(key, value) # -------------------------------------------------- # ✅ print last N key-value pairs of dict lastN = list(my_dict.items())[-2:] print(lastN) # 👉️ [('website', 'bobbyhadz.com'), ('topic', 'Python')]

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = {'id': 1, 'name': 'BobbyHadz'} print(my_dict.items()) # 👉️ dict_items([('id', 1), ('name', 'BobbyHadz')])

If you need to print only the key-value pairs of a dictionary that meet a condition, use a for loop to iterate over the dictionary's items.

main.py
my_dict = { 'name': 'Borislav Hadzhiev', 'fruit': 'apple', 'number': 5, 'website': 'bobbyhadz.com', 'topic': 'Python' } for key, value in my_dict.items(): if str(value).startswith('bo'): print(key, value) # 👉️ website bobbyhadz.com
On each iteration, we check if the current value starts with the string bo and if the condition is met, we print the key-value pair.

You can use a formatted string literal if you need to format the key-value pairs in any way.

main.py
my_dict = { 'name': 'Borislav Hadzhiev', 'fruit': 'apple', 'number': 5, 'website': 'bobbyhadz.com', 'topic': 'Python' } for key, value in my_dict.items(): if str(value).startswith('bo'): # 👇️ Key: website, Value: bobbyhadz.com print(f'Key: {key}, Value: {value}')

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
var1 = 'bobby' var2 = 'hadz' result = f'{var1}{var2}' print(result) # 👉️ bobbyhadz

Make sure to wrap expressions in curly braces - {expression}.

If you need to print a single key-value pair, use bracket notation or the dict.get() method.

main.py
my_dict = { 'name': 'Borislav Hadzhiev', 'fruit': 'apple', 'number': 5, 'website': 'bobbyhadz.com', 'topic': 'Python' } print(my_dict['name']) # 👉️ Borislav Hadzhiev print(my_dict.get('name')) # 👉️ Borislav Hadzhiev
When using bracket notation to access a dictionary key that doesn't exist, a KeyError is raised.

On the other hand, the dict.get() method returns None for non-existent keys by default.

The dict.get method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 parameters:

NameDescription
keyThe key for which to return the value
defaultThe default value to be returned if the provided key is not present in the dictionary (optional)

If a value for the default parameter is not provided, it defaults to None, so the get() method never raises a KeyError.

Print the first N key-value pairs of a dictionary #

To print the first N key-value pairs of a dictionary:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use the list() class to convert the view to a list.
  3. Use list slicing to get the first N key-value pairs.
  4. Use the print() function to print the result.
main.py
my_dict = { 'name': 'Borislav Hadzhiev', 'fruit': 'apple', 'number': 5, 'website': 'bobbyhadz.com', 'topic': 'Python' } firstN = list(my_dict.items())[:2] # 👇️ [('name', 'Borislav Hadzhiev'), ('fruit', 'apple')] print(firstN) for key, value in firstN: # name Borislav Hadzhiev # fruit apple print(key, value)

We used the list() class to convert the dictionary's items to a list and used list slicing to select the first N key-value pairs.

The syntax for list slicing is my_list[start:stop:step].

The start index is inclusive and the stop index is exclusive (up to, but not including).

Python indexes are zero-based, so the first item in a list has an index of 0, and the last item has an index of -1 or len(my_list) - 1.

You can use the same approach to print the last N key-value pairs of a dictionary.

main.py
my_dict = { 'name': 'Borislav Hadzhiev', 'fruit': 'apple', 'number': 5, 'website': 'bobbyhadz.com', 'topic': 'Python' } lastN = list(my_dict.items())[-2:] print(lastN) # 👉️ [('website', 'bobbyhadz.com'), ('topic', 'Python')] for key, value in lastN: # website bobbyhadz.com # topic Python print(key, value)

Negative indices can be used to count backward, e.g. my_list[-1] returns the last item in the list and my_list[-2] returns the second-to-last item.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.