AppDividend
Latest Code Tutorials

How to Print Dictionary Keys in Python

0

Python Dictionary items are presented in key: value pairs, they are ordered, modifiable, and do not allow duplicates. To find how many items a dictionary has, use the len() function.

How to Print Dictionary Keys in Python

To print the dictionary keys in Python, use the dict.keys() method to get the keys and then use the print() function to print those keys. The dict.keys() method returns a view object that displays a list of all the keys in the dictionary.

The dict.keys() method can be used to access the elements of the dictionary as we can do for a list by index.

Let’s define a dictionary and then use the dict.keys() and print() method to print the keys.

dict = {
    'streaming': 'Netflix',
    'show': 'Shadow and Bone',
    'ratings': 'Good',
    'genre': 'Fantasy '
}

print(dict.keys())

Output

dict_keys(['streaming', 'show', 'ratings', 'genre'])

And you get the list of dictionary keys.

Using dictionary.items() method

The dictionary items() a built-in Python method used to get all the keys and associated values with those keys. We can use the items() method with for loop and print the keys and values of the dictionary.

If you want to print a key one at a time then this approach is more useful.

dict = {
    'streaming': 'Netflix',
    'show': 'Shadow and Bone',
    'ratings': 'Good',
    'genre': 'Fantasy '
}

for key, value in dict.items():
    print(key)

Output

streaming
show
ratings
genre

To print the keys and values of the dictionary, use the dict.items() method.

To print the keys of the dictionary, use the dict.keys() method.

To print the values of the dictionary, use the dict.values() method.

These are the Pythonic ways to get the keys and values out of the dictionary object.

That’s it for this tutorial.

Leave A Reply

Your email address will not be published.

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