Iterate Through a Dictionary in Python
In Python, you can loop through a dictionary in several ways, depending on whether you need to access its keys, values, or both. Here are the common methods:
Iterate Through Keys (Default Behavior)
When you iterate directly over a dictionary using a for loop, it returns the keys by default.
For example:
person = {"name": "James", "age": 30, "location": "London"}
for key in person:
print(key)
Output:
name
age
location
You can also call the .keys() method explicitly to get the keys.
person = {"name": "James", "age": 30, "location": "London"}
for key in person.keys():
print(key)
Output:
name
age
location
You can use each key inside the loop to access its value.
person = {"name": "James", "age": 30, "location": "London"}
for key in person:
print(f"Key: {key}, Value: {person[key]}")
Output:
Key: name, Value: James
Key: age, Value: 30
Key: location, Value: London
Iterate Through Values
If you only need the values, you can use the .values() method.
For example:
person = {"name": "James", "age": 30, "location": "London"}
for value in person.values():
print(value)
Output:
James
30
London
Iterate Through Key-Value Pairs
If you need both keys and values, you can use the .items() method.
For example:
person = {"name": "James", "age": 30, "location": "London"}
for key, value in person.items():
print(f"Key: {key}, Value: {value}")
Output:
Key: name, Value: James
Key: age, Value: 30
Key: location, Value: London