Python: Print all key-value pairs of a dictionary

In this article, we will learn about different ways to print all items (key-value pairs) of a dictionary.

Table of Contents

Print all pairs of dictionary using for loop and items()

The items() function of dictionary class returns an iterable sequence of all key-value pairs of dictionary. We can use a for loop to iterate over this sequence of pairs and print each of them one by one. For example,

# Dictionary of string and int
word_freq = {
    'Hello' : 56,
    "at"    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

# Print all key-value pairs of a dictionary
for key, value in word_freq.items():
    print(key, '::', value)

Output:

Hello :: 56
at :: 23
test :: 43
This :: 78
Why :: 11

It printed all the key-value items of dictionary.

Advertisements

Print all pairs of dictionary by iterating over keys only

We can also iterate over all keys of the dictionary using a for loop and during iteration select value of each key using [] operator, then print the pair. For example,

# Dictionary of string and int
word_freq = {
    'Hello' : 56,
    "at"    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

# Print all key-value pairs of a dictionary
for key in word_freq:
    print(key, '::', word_freq[key])

Output:

Hello :: 56
at :: 23
test :: 43
This :: 78
Why :: 11

It print all the key-value items of dictionary. But it is less effective solution than the previous one.

Print all pairs of dictionary in reverse order

We can create a list of all key-value pairs of dictionary by passing the iterable sequence returned by items() function to the list() function. Then we can reverse the contents of pairs and print them. For example,

# Dictionary of string and int
word_freq = {
    'Hello' : 56,
    "at"    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

# Get all key-value pairs of dictionary as list
all_pairs = list(word_freq.items())

# Iterate over the reversed list of key-value pairs 
# and print them one by one
for key, value in reversed(all_pairs):
    print(key, '::', value)

Output:

Why :: 11
This :: 78
test :: 43
at :: 23
Hello :: 56

It print all the key-value items of dictionary in reverse order. We created a list because the iterable sequence dict_items, returned by the items() function is non reversible.

Print all key-value pairs of a nested dictionary

Suppose we have a dictionary that contains other dictionaries as values. To print all key-value pairs of this dictionary we have created a function, that will recursively go inside the nested dictionary and print all key-value pairs. For example,

# A Nested dictionary i.e. dictionaty of dictionaries
students = {
            'ID 1':    {'Name': 'Shaun', 'Age': 35, 'City': 'Delhi'},
            'ID 2':    {'Name': 'Ritika', 'Age': 31, 'City': 'Mumbai'},
            'ID 3':    {'Name': 'Smriti', 'Age': 33, 'City': 'Sydney'},
            'ID 4':    {'Name': 'Jacob', 'Age': 23, 'City': {'perm': 'Tokyo', 'current': 'London'}},
            }

def print_all_pairs(dict_obj):
    ''' This function print all key-value pairs
        of a nested dictionary i.e. dict of dicts
    '''
    # Iterate over all key-value pairs of a dict
    for key, value in dict_obj.items():
        # If value is of dict type then print 
        # all key-value pairs in the nested dictionary
        if isinstance(value, dict):
            print_all_pairs(value)
        else:
            print(key, '::', value)


print_all_pairs(students)

Output:

Name :: Shaun
Age :: 35
City :: Delhi
Name :: Ritika
Age :: 31
City :: Mumbai
Name :: Smriti
Age :: 33
City :: Sydney
Name :: Jacob
Age :: 23
perm :: Tokyo
current :: London

Summary:

We learned about different ways to print all key-value pairs of a dictionary.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top