Looping Through Dictionaries

You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value is the key of the dictionary, but there are methods to access keys and values.

Looping Through Keys

Example: Iterating Over Keys

# Looping through dictionary keys
person = {"name": "Karthick AG", "age": 30, "city": "Chennai"}
for key in person:
    print("Key:", key)

Key: name

Key: age

Key: city

Looping Through Values

Example: Iterating Over Values

# Looping through dictionary values
for value in person.values():
    print("Value:", value)

Value: Karthick AG

Value: 30

Value: Chennai

Looping Through Key-Value Pairs

Example: Iterating Over Items

# Looping through key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

name: Karthick AG

age: 30

city: Chennai

Explanation: Using the items() method, you can loop through both keys and values of the dictionary simultaneously.