Python Loop Dictionaries

Why Loop Through a Dictionary?

In Python, you can loop through a dictionary to:

  • Get keys
  • Get values
  • Get key-value pairs

Example 1: Loop Through Keys

person = {
 "name": "Alice",
 "age": 25,
 "city": "New York"
}
for key in person:
   print(key)

Output:

name
age
city

Explanation: Looping directly over the dictionary returns its keys

Example 2: Access Values Using Keys

person = {
 "name": "Alice",
 "age": 25,
 "city": "New York"
}
for key in person:
   print(person[key])

Output:

Alice
25
New York

Explanation: Use person[key] inside the loop to get the corresponding value.

Example 3: Use .values() to Loop Through Values

person = {
 "name": "Alice",
 "age": 25,
 "city": "New York"
}
for value in person.values():
   print(value)

Output:

Alice
25
New York

Explanation: .values() returns all the values in the dictionary.

Example 4: Use .keys() to Loop Through Keys Explicitly

person = {
 "name": "Alice",
 "age": 25,
 "city": "New York"
}
for key in person.keys():
   print(key)

Output:

name
age
city

Explanation: .keys() is similar to the default loop, but explicit.

Example 5: Use .items() to Loop Through Key-Value Pairs

person = {
 "name": "Alice",
 "age": 25,
 "city": "New York"
}
for key, value in person.items():
   print(f"{key}: {value}")

Output:

name: Alice
age: 25
city: New York

Explanation: .items() returns key-value pairs, which can be unpacked in the loop.

Example 6: Conditional Logic While Looping

person = {
 "name": "Alice",
 "age": 25,
 "city": "New York"
}
for key, value in person.items():
   if key == "age":
       print("Age found:", value)

Output:

Age found: 25

Explanation: You can add if conditions inside the loop to check for specific keys or values.

Summary Table

Loop MethodWhat It Returns
for key in dictKeys
dict.keys()Keys
dict.values()Values
dict.items()Key-value pairs (tuple)

Conclusion

Looping through dictionaries is essential when you need to access or process key-value data. Use .items() for pairs, .keys() or default for keys, and .values() for values.