Iterating Over a Dictionary in Python

A dictionary in Python is very similar to a dictionary in the real world. You have a key and a definition. It is accessed by a key and not a definition.

There are a few ways you can loop through dictionaries in Python 3.

Example dictionary:

person = {
    "firstname": "John",
    "lastname": "Smith",
    "age": 45,
    "employee": True
}

Iterate over keys

for key in person:
    print("{}: {}".format(key, person[key]))

output

firstname: John
lastname: Smith
age: 45
employee: True

Iterate over values

for value in person.values():
    print(value)

output

John
Smith
45
True

Iterate over key/value pairs

for key, value in person.items():
    print("{}: {}".format(key, value))

output

firstname: John
lastname: Smith
age: 45
employee: True

Iterate over keys in sorted order

for key in sorted(person):
    print("{}: {}".format(key, person[key]))

output

age: 45
employee: True
firstname: John
lastname: Smith

Iterate over nested dictionary

You can also iterate through a nested dictionary.

Nested dictionary example:

mydict = {
     'person1': {
         'firstname': 'John',
         'lastname': 'Smith'
     },
     'person2': {
         'firstname': 'Andrew',
         'lastname': 'Williams'}
     }

code

for key1, value1 in mydict.items():
    temp = ""
    temp += key1
    for key2, value2 in value1.items():
        temp = temp + " " + str(key2) + ": " + str(value2) + ', '
    print(temp)

output

person1 firstname: John,  lastname: Smith,
person2 firstname: Andrew,  lastname: Williams,