![]() |
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 ValuesBelow, are the ways of Python Print Dictionary Keys and Values in Python.
Python Print Dictionary Keys and Values Using
|
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) |
Keys: ['a', 'b', 'c'] Values: [1, 2, 3] Keys and Values: {'a': 1, 'b': 2, 'c': 3}
L
oopIn 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.
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}" ) |
Keys and Values: a: 1 b: 2 c: 3
zip()
FunctionIn 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.
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}" ) |
Keys and Values: a: 1 b: 2 c: 3
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.
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |