Iterating Through Python Dictionaries with Examples

Python Python Basics

Python dictionaries support various ways to iterate through their key-value pairs. This can be particularly useful when you need to perform an operation on each item in the dictionary.

Table of Contents

Using items() Method

The items() method returns a list of tuples, where each tuple contains a key-value pair:


for key, value in my_dict.items():
    print(f'Key: {key}, Value: {value}')

Using keys() and values() Methods

You can also iterate through keys and values separately using the keys() and values() methods:


for key in my_dict.keys():
    print(f'Key: {key}')

for value in my_dict.values():
    print(f'Value: {value}')

Using a For Loop with Dictionary Keys

You can also use a for loop directly with dictionary keys:


for key in my_dict:
    print(f'Key: {key}, Value: {my_dict[key]}')

Iterating Through Dictionary Items as Strings

If you need to iterate through the items of a dictionary as strings (i.e., keys), you can use the items() method and convert each tuple to a string using the str() function:


for item in my_dict.items():
    print(str(item))  # Output: ('name', 'John Doe')

Iterating Through Dictionary Items as Tuples or Lists

If you need to iterate through the items of a dictionary as tuples or lists, you can convert the dictionary to a list of tuples or list of lists using the items() method and list comprehension:


# To a list of tuples
list_of_tuples = list(my_dict.items())
for item in list_of_tuples:
    print(item)  # Output: ('name', 'John Doe')

# To a list of lists
list_of_lists = [list(i) for i in my_dict.items()]
for item in list_of_lists:
    print(item)  # Output: ['name', 'John Doe']

Conclusion

Python dictionaries offer various ways to iterate through their key-value pairs, making it easy to perform operations on each item. Understanding these methods can help you effectively manipulate and process data stored in dictionaries.

To top