Iterate Through Dictionary Keys And Values in Python
Below, are the possible approaches to Iterate Through Dictionary Keys And Values In Python.
- Using list comprehension
- Using keys() and values() methods
- Using the zip() method
Iterate Through a Dictionary Using List Comprehension
The below approach code uses list comprehension and the items() method on a dictionary in Python to iterate through its keys and values. The for loop in list comprehension iterates through all the keys and values and prints all the key-value pairs in a dictionary format.
Python3
# defining dictionary related to w3wiki geeks_data = { 'language' : 'Python' , 'framework' : 'Django' , 'topic' : 'Data Structures' } keys = [key for key in geeks_data.keys()] values = [value for value in geeks_data.values()] # Print keys print ( "Keys:" ) for key in keys: print (key) # Print values print ( "\nValues:" ) for value in values: print (value) |
Keys: language framework topic Values: Python Django Data Structures
Iterate Through a Dictionary Using keys() and values() Methods
The below approach code uses keys( ) and values() methods to iterate through all the keys and values of the dictionary (d). The d.keys( ) returns all the keys whereas the values() method returns all the values of the dictionary. The for loop iterates through all the keys and prints all the keys and values.
Python3
# defining dictionary related to w3wiki geeks_data = { 'language' : 'Python' , 'framework' : 'Django' , 'topic' : 'Data Structures' } # Iterate through keys print ( "Keys:" ) for key in geeks_data.keys(): print (key) # Iterate through values print ( "\nValues:" ) for value in geeks_data.values(): print (value) |
Keys: language framework topic Values: Python Django Data Structures
Iterate Through a Dictionary Using zip( ) Function
The belew approach code defines a dictionary and then uses the zip() method to unzip the keys and values. Finally, it prints the keys and values separately using list comprehensions.
Python3
# defining dictionary related to w3wiki geeks_data = { 'language' : 'Python' , 'framework' : 'Django' , 'topic' : 'Data Structures' } keys, values = zip ( * geeks_data.items()) print ( "Keys:" ) _ = [ print (key) for key in keys] print ( "\nValues:" ) _ = [ print (value) for value in values] |
Keys: language framework topic Values: Python Django Data Structures
Iterate Through Dictionary Keys And Values In Python
In Python, a Dictionary is a data structure where the data will be in the form of key and value pairs. So, to work with dictionaries we need to know how we can iterate through the keys and values. In this article, we will explore different approaches to iterate through keys and values in a Dictionary in Python.