Skip to content

How to Print Specific Key-Value Pairs from Python Dictionaries

Learn how to extract and print specific key-value pairs from Python dictionaries using conditions, slicing, and formatting techniques.

This guide explores various techniques for printing specific key-value pairs from Python dictionaries. We'll cover filtering based on conditions, printing the first or last N pairs, extracting a slice of the dictionary, and using formatting to present the output clearly.

Printing Key-Value Pairs Based on Conditions

To print key-value pairs that meet a specific condition, iterate over the dictionary's items:

my_dict = {
    'name': 'Tom Nolan',
    'fruit': 'apple',
    'number': 5,
    'website': 'tutorialreference.com',
    'topic': 'Python'
}

for key, value in my_dict.items():
    if str(value).startswith('tu'): # Check if the value starts with "tu"
        print(key, value)           # Output: website tutorialreference.com
  • my_dict.items() returns a view object containing key-value tuples.
  • The for loop iterates through the tuples, unpacking the key and value.
  • The if statement checks if the string representation of the value starts with "bo".
  • Matching key-value pairs are printed.

Formatting the Output

Use f-strings for formatted printing:

my_dict = {
    'name': 'Tom Nolan',
    'fruit': 'apple',
    'number': 5,
    'website': 'tutorialreference.com',
    'topic': 'Python'
}

for key, value in my_dict.items():
    if str(value).startswith('bo'):
        print(f'Key: {key}, Value: {value}')

Printing a Single Key-Value Pair

Access a specific value using bracket notation ([]) or get():

my_dict = {
    'name': 'Tom Nolan',
    'fruit': 'apple',
    'number': 5,
    'website': 'tutorialreference.com',
    'topic': 'Python'
}

print(my_dict['name'])              # Output: Tom Nolan
print(my_dict.get('name'))          # Output: Tom Nolan

print(my_dict.get('nonexistent'))   # Output: None (get() returns None by default)
  • Bracket notation raises KeyError if the key doesn't exist, while get() returns None by default.

Printing the First N Key-Value Pairs

To print the first N items, convert the items view to a list and use slicing:

my_dict = {
    'name': 'Tom Nolan',
    'fruit': 'apple',
    'number': 5,
    'website': 'tutorialreference.com',
    'topic': 'Python'
}

firstN = list(my_dict.items())[:2]  # Get the first 2 pairs
print(firstN)                       # Output: [('name', 'Tom Nolan'), ('fruit', 'apple')]

for key, value in firstN:
    print(key, value)
  • The list() constructor converts the view returned by .items() into a list.
  • The slice [:2] gets the first 2 elements from the list.

Printing the Last N Key-Value Pairs

Use negative slicing to print the last N items:

my_dict = {
    'name': 'Tom Nolan',
    'fruit': 'apple',
    'number': 5,
    'website': 'tutorialreference.com',
    'topic': 'Python'
}

lastN = list(my_dict.items())[-2:]  # Get the last 2 pairs
print(lastN)                        # Output: [('website', 'tutorialreference.com'), ('topic', 'Python')]

for key, value in lastN:
    print(key, value)
  • The slice [-2:] selects the last two elements.

Printing a Slice of a Dictionary

To extract an arbitrary slice (a sub-dictionary) based on insertion order:

Using List Slicing

Convert items to a list, slice, then convert back to a dictionary:

my_dict = {
    'id': 1,
    'age': 30,
    'salary': 100,
    'name': 'tutorialreference',
    'language': 'Python'
}

result = dict(list(my_dict.items())[1:4])   # Slice from index 1 up to 4
print(result)                               # Output: {'age': 30, 'salary': 100, 'name': 'tutorialreference'}
  • The slice [1:4] selects items from index 1 up to (but not including) index 4.
  • dict(...) converts the sliced list of tuples back into a dictionary.

Using itertools.islice()

For potentially large dictionaries, itertools.islice() is more memory-efficient as it works with iterators:

from itertools import islice

a_dict = {
    'id': 1,
    'first': 'tom',
    'last': 'reference',
    'site': 'tutorialreference.com',
    'topic': 'python'
}

new_dict = dict(islice(a_dict.items(), 2))      # First 2 items
print(new_dict)                                 # Output: {'id': 1, 'first': 'tom'}

new_dict = dict(islice(a_dict.items(), 2, 4))   # Items from index 2 up to 4
print(new_dict)                                 # Output: {'last': 'reference', 'site': 'tutorialreference.com'}
  • islice() returns an iterator containing the specified slice of the dictionary's items.
  • The dict() constructor takes the iterator returned by islice() and converts it to a new dictionary.

Printing by Excluding Keys

Use a dictionary comprehension to create a new dictionary without specific keys:

my_dict = {
    'id': 1,
    'age': 30,
    'salary': 100,
    'name': 'tutorialreference',
    'language': 'Python'
}

def exclude_keys(dictionary, keys_to_exclude):
    return {
        key: value for key, value in dictionary.items()
        if key not in keys_to_exclude
    }

result = exclude_keys(my_dict, ['id', 'age'])
print(result)
  • The comprehension iterates through my_dict.items(), keeping only pairs where the key is not in the keys_to_exclude list.
Navigation