Last updated: Apr 9, 2024
Reading timeยท6 min
To print specific key-value pairs of a dictionary:
dict.items()
method to get a view of the dictionary's items.for
loop to iterate over the view.print()
function to print the matching key-value pairs.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
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
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.
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.
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
.
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.
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
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:
Name | Description |
---|---|
key | The key for which to return the value |
default | The 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
.
To print the first N key-value pairs of a dictionary:
dict.items()
method to get a view of the dictionary's items.list()
class to convert the view to a list.print()
function to print the result.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).
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.
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.
To only print a part of a dictionary:
dict.items()
method to get a view of the dictionary's items.print()
function to print the result.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 dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
my_dict = {'id': 1, 'name': 'BobbyHadz'} print(my_dict.items()) # ๐๏ธ dict_items([('id', 1), ('name', 'BobbyHadz')])
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
.
If you need to exclude certain keys from the dictionary and print the result, use a dict comprehension.
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)
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.
This is a three-step process:
dict.items()
method to get a view of the dictionary's items.itertools.islice()
method to get a slice of the view object.dict()
class to convert the slice to a dictionary.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 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).
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.
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 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.
You can learn more about the related topics by checking out the following tutorials: