In this article, we will see how to print the keys and values of a dictionary.
There are several methods in python to achieve this task.
Using the keys() and values() methods
There might be case where you need only the keys or values of a dictionary. In such a case you can use the keys() and values() methods to fetch only keys or values of a dictionary.
Following is the example program to print either keys or values of a dictionary.
d = {'name': 'Abhi', 'age': 30, 'city': 'Bangalore'}
# Printing only the keys
print("Keys:")
for key in d.keys():
print(key)
# Printing only the values
print("Values:")
for value in d.values():
print(value)
Ouput:
Keys:
name
Abhi
city
Values:
John
30
Bangalore
Using the items() method:
This is an easiest way to print a dictionary’s keys and values. The items() method returns a list of key-value pairs from the dictionary as tuples. Here’s an example program:
d = {'name': 'Abhi', 'age': 30, 'city': 'Bangalore'}
for key, value in d.items():
print(f"{key}: {value}")
name: Abhi
age: 30
city: Bangalore
Using iteritems():
This is pretty similar to items() method. The only difference is items() return the entire list where as iteritems() return an iterator.
Iterators are used to iteratively traverse a collection of elements, such as a list, tuple, or dictionary. Because they do not load all elements into memory at once, they are a more efficient alternative to looping over the elements of a collection. Instead, the elements are loaded one by one as needed.
This can be useful if you’re working with a large dictionary where you don’t need to create a list in memory.
d = {'name': 'Abhi', 'age': 30, 'city': 'Bangalore'}
for key, value in d.iteritems():
print(f"{key}: {value}")
Output
name: John
age: 30
city: New York