Open In App

Python Print Dictionary Keys and Values

Last Updated : 25 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python, a versatile and powerful programming language, offers multiple ways to interact with and manipulate data structures. Among these, dictionaries are widely used for storing key-value pairs. When working with dictionaries, it’s essential to be able to print their keys and values for better understanding and debugging. In this article, we’ll explore different methods to Print Dictionary Keys and Values.

Python Print Dictionary Keys and Values

Below, are the ways of Python Print Dictionary Keys and Values in Python.

Python Print Dictionary Keys and Values Using print() Method

In this example, below Python code defines a dictionary `my_dict` with key-value pairs. It then prints the keys, values, and the entire dictionary. The `list()` function is used to convert the dictionary’s keys and values into lists for display.

Python3




my_dict = {'a': 1, 'b': 2, 'c': 3}
 
# Print keys
print("Keys:", list(my_dict.keys()))
 
# Print values
print("Values:", list(my_dict.values()))
 
# Print both keys and values
print("Keys and Values:")
print(my_dict)


Output

Keys: ['a', 'b', 'c']
Values: [1, 2, 3]
Keys and Values:
{'a': 1, 'b': 2, 'c': 3}


Python Print Dictionary Keys and Values Using Loop

In this example , below Python code uses a loop to iterate through the keys and values of the dictionary `my_dict` and prints them in a formatted manner. The `items()` method is employed to simultaneously iterate over both keys and values, and f-strings are used for concise printing.

Python3




my_dict = {'a': 1, 'b': 2, 'c': 3}
 
# Print both keys and values
print("Keys and Values:")
for key, value in my_dict.items():
    print(f"{key}: {value}")


Output

Keys and Values:
a: 1
b: 2
c: 3


Python Print Dictionary Keys and Values Using zip() Function

In this example, below Python code uses the `zip()` function to pair keys and values from the dictionary `my_dict` and then prints them in a formatted manner. This approach allows for simultaneous iteration over keys and values, enhancing code conciseness.

Python3




my_dict = {'a': 1, 'b': 2, 'c': 3}
 
# Print both keys and values using zip()
print("Keys and Values:")
for key, value in zip(my_dict.keys(), my_dict.values()):
    print(f"{key}: {value}")


Output

Keys and Values:
a: 1
b: 2
c: 3


Conclusion

In conclusion, Python offers various methods to print dictionary keys and values, providing flexibility depending on your specific requirements. Whether you prefer simplicity, control, or concise formatting, these methods enable you to effectively work with dictionaries in Python.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads