How To Print All Values In A Dictionary In Python

To print all values in a dictionary in Python, you can use the dict.values(), dict.keys(), dict.items() functions. Follow the explanation below to understand better.

Print All Values In A Dictionary In Python

Using the dict.values() function

You can use the dict.values() function to print all values in a dictionary in Python. First, you get the list of values with the dict.values() function. Then, print all values with the join() function, list comprehension, or for loop. We will use the join() function in this example.

Look at the example below.

# Create a dictionary.
dictionary = {
    'Cat': 'Yellow',
    'Dog': 'Yellow',
    'Duck': 'White',
    'Pig': 'White',
    'Raven': 'Black'
}

# Get all values of the dictionary with the dict.values() function.
values = dictionary.values()

# Print all values of the dictionary.
print(', '.join(values))

Output

Yellow, Yellow, White, White, Black

Using the dict.items() function

Besides the dict.values() function, you can use the dict.items() instead to print all values in a dictionary. The dict.items() function returns a list of tuples. A tuple has two elements: the first is the key and the second is the value. So, you can print the values of the dictionary by printing the second element of the tuple.

Look at the example below.

# Create a dictionary.
dictionary = {
    'Cat': 'Yellow',
    'Dog': 'Yellow',
    'Duck': 'White',
    'Pig': 'White',
    'raven': 'Black'
}

# Print all values in a dictionary with the dict.items() function.
for key, value in dictionary.items():
    print(value, end=' ')

Output

Yellow Yellow White White Black 

Using the dict.keys() function

In addition, you can use the dict.keys() function to print all values in a dictionary in Python. It returns a list of keys in the dictionary. You can get the value directly through the key by the square brackets. In this example, we get a list of keys with the dict.keys() function first. After then, we will iterate this list to get the values of the initial dictionary.

Look at the example below.

# Create a dictionary.
dictionary = {
    'Cat': 'Yellow',
    'Dog': 'Yellow',
    'Duck': 'White',
    'Pig': 'White',
    'raven': 'Black'
}

# Get the list of keys with the dict.keys() function.
keys = dictionary.keys()

# Print all the values of the dictionary.
for key in keys:
    print(dictionary[key], end=' ')

Output

Yellow Yellow White White Black 

Summary

We have shown you how to print all values in a dictionary in Python. In our opinion, you should use the dict.values() function because you can get the list of values in one step. So your responsibility is to print out these values. We hope this tutorial is helpful to you. Thanks!

Leave a Reply

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