How to Print Specific Key-Value Pairs of a Dictionary in Python?

Estimated read time 2 min read

To print specific key-value pairs of a dictionary in Python, you can use a loop to iterate over the dictionary and print only the key-value pairs that meet your criteria.

Here’s an example code snippet that demonstrates how to print specific key-value pairs of a dictionary:

# define a dictionary
my_dict = {'apple': 2, 'banana': 4, 'orange': 6, 'grape': 8}

# print key-value pairs where the value is greater than 4
for key, value in my_dict.items():
    if value > 4:
        print(key, value)

This code will output:

orange 6
grape 8

You can modify the condition in the if statement to print key-value pairs that meet different criteria. For example, you could print key-value pairs where the key is ‘banana’:

# print key-value pairs where the key is 'banana'
for key, value in my_dict.items():
    if key == 'banana':
        print(key, value)

This code will output:

banana 4

You can also use dictionary comprehension to create a new dictionary that contains only the key-value pairs that meet your criteria. For example, you could create a new dictionary that contains only the key-value pairs where the value is greater than 4:

# create a new dictionary with key-value pairs where the value is greater than 4
new_dict = {key: value for key, value in my_dict.items() if value > 4}

# print the new dictionary
print(new_dict)

This code will output:

{'orange': 6, 'grape': 8}

Again, you can modify the condition in the if statement to create a new dictionary that contains key-value pairs that meet different criteria.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply