Python: Print Specific Key-Value Pairs of Dictionary

Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

Given a dictionary, the task is to print specific key-value pairs of the Dictionary.

Display Specific Key-Value Pairs of Dictionary

Indexing:

Dictionary’s items() function returns an iterable sequence of dictionary key-value pairs, i.e. dict items. However, this is a view-only sequence, and we cannot use indexing on it. So, if we want to use indexing to select items from a dictionary, we must first create a list of pairs from this sequence.

We can convert dictionary items to list using list() function

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictlist = list(dictionary.items())
# using indexing we can print the first key value pair of dictionary
print("1st key value pair :", dictlist[0])

Output:

1st key value pair : ('this', 200)

We can print last key value pair of dictionary using negative indexing(-1) or using length function of list.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictlist = list(dictionary.items())
# using indexing we can print the last key value pair of dictionary
print("last key value pair :", dictlist[-1])

Output:

last key value pair : ('BTechGeeks', 300)

We can print nth key-value pair using indexing

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# given n
n = 2
# convert the dictionary to list using items()
dictlist = list(dictionary.items())
# using indexing we can print the nth key value pair of dictionary
print("nth key value pair :", dictlist[n-1])

Output:

nth key value pair : ('is', 100)

4)Printing specific key-value pairs based on given conditions

To print specific dictionary items that satisfy a condition, we can iterate over all dictionary pairs and check the condition for each pair. If the condition returns True, then print the pair otherwise, skip it.

Let us print all the key-value pairs whose value is greater than 100

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# convert the dictionary to list using items()
dictlist = list(dictionary.items())
# Traverse the dictionary
for key, value in dictionary.items():
    # if the value is greater than 100 then print it
    if(value > 100):
        print(key, value)

Output:

this 200
BTechGeeks 300

Related Programs: