Here are the ways to iterate over the Dictionary in Python:
- Iterate Over Key-Value Pairs Using .items() Method
- Iterate Over Keys Using .keys() Method
- Iterate Over Values using .values() Method
- Using List Comprehension
- Enumerating Items
Method 1: Iterate Over Key-Value Pairs Using .items() Method
The dict.items() method returns a view object that consists of a dictionary’s (key, value) tuple pairs.
We can use a for-loop to iterate over these key-value pairs.
Visual Representation
Example
sample_dict = {
'name': 'Jon',
'country': 'USA',
'age' : 23
}
for data_keys, data_values in sample_dict.items():
print(f"{data_keys}: {data_values}")
Output
name: Jon
country: USA
age: 23
Method 2: Iterate Over Keys Using .keys() Method
If you need to work with the keys, you can use the dict.keys() method, which returns a view object containing the dictionary’s keys.
Visual Representation
Example
sample_dict = {
'name': 'Jon',
'country': 'USA',
'Age' : 23
}
data_keys = sample_dict.keys()
print(data_keys)
Output
dict_keys(['name', 'country', 'Age'])
We can iterate over data_keys with a for-loop.
sample_dict = {
'name': 'Jon',
'country': 'USA',
'age' : 23
}
data_keys = sample_dict.keys()
for key in data_keys:
print(key)
Output
name
country
age
Method 3: Iterate Over Values using .values() Method
The dict.values() method returns a view object that displays all the values in the dictionary.
You can then use a for-loop to iterate over these values.
Visual Representation
Example
sample_dict = {
'name': 'Jon',
'country': 'USA',
'age' : 23
}
for data_values in sample_dict.values():
print(data_values)
Output
Jon
USA
23
Method 4: Using List Comprehension
If you want a list of keys and values, you can use list comprehensions to iterate over the dictionary.
Example
sample_dict = {
'name': 'Jon',
'country': 'USA',
'age' : 23
}
# Creating a list of keys
keys_list = [k for k in sample_dict]
# Creating a list of values
values_list = [v for v in sample_dict.values()]
print("Keys List:",keys_list)
print("Values List:",values_list)
Output
Keys List: ['name', 'country', 'age']
Values List: ['Jon', 'USA', 23]
Method 5: Enumerating Items
If you need index with your iteration, use enumerate() on .items().
Visual Representation
Example
sample_dict = {
'name': 'Jon',
'country': 'USA',
'Age' : 23
}
for index, (data_keys, data_values) in enumerate(sample_dict.items()):
print(f"{index} -> {data_keys}: {data_values}")
Output
0 -> name: Jon
1 -> country: USA
2 -> Age: 23