Print specific key-value pairs of a dictionary in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
6 min

banner

# Table of Contents

  1. Print specific key-value pairs of a dictionary in Python
  2. Formatting the key-value pairs when printing them
  3. Print the first N key-value pairs of a dictionary
  4. Print the last N key-value pairs of a dictionary
  5. Print only a part of a dictionary using slicing
  6. Print only a part of a dictionary by excluding keys
  7. Slicing a dictionary with itertools.islice()

# 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 specific key value pairs of dictionary

The code for this article is available on GitHub

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.

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.

# Formatting the key-value pairs when printing them

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}')

format key value pairs when printing them

The code for this article is available on GitHub

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

printing single key value pair

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)

print first n key value pairs of dictionary

The code for this article is available on GitHub

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.

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

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)

print last n key value pairs of dictionary

The code for this article is available on GitHub

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.

# Print only a part of a dictionary using slicing

To only print a part of a dictionary:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Convert the view to a list and use list slicing to get a part of the dictionary.
  3. Use the print() function to print the result.
main.py
my_dict = { 'id': 1, 'age': 30, 'salary': 100, 'name': 'bobbyhadz', 'language': 'Python' } result = dict(list(my_dict.items())[0:3]) print(result) # ๐Ÿ‘‰๏ธ {'id': 1, 'age': 30, 'salary': 100}
The code for this article is available on GitHub

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')])
We used the list() class to convert the view object to a list and used list slicing to select the first 3 items in the dictionary.

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.

# Print only a part of a dictionary by excluding keys

If you need to exclude certain keys from the dictionary and print the result, use a dict comprehension.

main.py
my_dict = { 'id': 1, 'age': 30, 'salary': 100, 'name': 'bobbyhadz', 'language': 'Python' } def exclude_keys(dictionary, keys): return { key: value for key, value in dictionary.items() if key not in keys } result = exclude_keys(my_dict, ['id', 'age']) # ๐Ÿ‘‡๏ธ {'salary': 100, 'name': 'bobbyhadz', 'language': 'Python'} print(result)
The code for this article is available on GitHub

We used a dict comprehension to iterate over the dictionary's items and excluded the specified keys.

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

# Slicing a dictionary with itertools.islice()

This is a three-step process:

  1. Use the dict.items() method to get a view of the dictionary's items.
  2. Use the itertools.islice() method to get a slice of the view object.
  3. Use the dict() class to convert the slice to a dictionary.
main.py
from itertools import islice a_dict = { 'id': 1, 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'python' } # โœ… slice dictionary based on index new_dict = dict(islice(a_dict.items(), 2)) print(new_dict) # ๐Ÿ‘‰๏ธ {'id': 1, 'first': 'bobby'} new_dict = dict(islice(a_dict.items(), 2, 4)) print(new_dict) # ๐Ÿ‘‰๏ธ {'last': 'hadz', 'site': 'bobbyhadz.com'}
The code for this article is available on GitHub

The first example uses the itertools.islice() method to slice a dictionary.

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

main.py
a_dict = { 'id': 1, 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'python' } # ๐Ÿ‘‡๏ธ dict_items([('id', 1), ('first', 'bobby'), ('last', 'hadz'), ('site', 'bobbyhadz.com'), ('topic', 'python')]) print(a_dict.items())

The itertools.islice method takes an iterator and optional start and stop indices.

The method makes an iterator that returns the selected elements from the iterable.
main.py
from itertools import islice a_dict = { 'id': 1, 'first': 'bobby', 'last': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'python' } new_dict = dict(islice(a_dict.items(), 2)) print(new_dict) # ๐Ÿ‘‰๏ธ {'id': 1, 'first': 'bobby'} new_dict = dict(islice(a_dict.items(), 2, 4)) print(new_dict) # ๐Ÿ‘‰๏ธ {'last': 'hadz', 'site': 'bobbyhadz.com'}

Dictionaries preserve the insertion order of keys starting with Python v3.7.

We used a start index of 2 and a stop index of 4.

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

The last step is to pass the slice to the dict() class.

The dict() class can be passed an iterable of key-value pairs and returns a new dictionary.

I've also written an article on how to print a dictionary in table format.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev