Print all Key-Value Pairs of a Dictionary

Python: Print all Key-Value Pairs of a 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 all key and values of the dictionary.

Examples:

Input:

dictionary = {"this": 100, "is": 200, "BTechGeeks": 300}

Output:

This 100
is 200
BTechGeeks 300

Display all Key-value pairs of a Dictionary

There are several ways to traverse the dictionary some of them are:

Method #1: Using for loop (iterating over keys only)

To iterate over all keys in a dictionary, a dictionary object can also be used as an iterable object. As a result, we can use for loop on a dictionary with ease. It loops through all of the keys in the dictionary using for in the dictionary. We will print the value associated with each key.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Using for loop to traverse the dictionary
for key in dictionary:
    # Getting value at key
    value = dictionary[key]
    # printing values and keys
    print(key, value)

Output:

This 100
is 200
BTechGeeks 300

Method #2:Using for loop and items()

The items() function of the dictionary class returns an iterable sequence of all key-value pairs within the dictionary. We can use a for loop to iterate through this list of pairs and print them one by one.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}

# Printing all key-value pairs
for key, value in dictionary.items():
    print(key, value)

Output:

This 100
is 200
BTechGeeks 300

Method #3:Using List Comprehension

Since the items() function of a dictionary returns an iterable sequence of key-value pairs, we may use this list comprehension to iterate over all diction pairs.

Below is the implementation:

# Given dictionary 
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300} 
# Using list comprehension 
[print(key, value) for key, value in dictionary.items()]

Output:

This 100
is 200
BTechGeeks 300
# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Using items and converting dictionary to list
dictlist = list(dictionary.items())
# traversing in reversed of this list
for key, value in reversed(dictlist):
    print(key, value)

Output:

BTechGeeks 300
is 200
This 100

Related Programs: