Python Iterate Dictionary Tutorial

In this section, we will learn how to iterate through the entries of a dictionary in Python.

Iterate Dictionary Python: Python for Loop Dictionary

In Python, we can use the `for` loop to iterate through the elements of a dictionary object.

But there are a couple of notes to remember:

  • If the purpose of iteration is to get the values of a dictionary, then we have two choices: 1- we can use the dictionary itself as the iterable object for the for loop. 2- we can call the `values()` method to get the sequence of values of the target dictionary and use that as the iterable object of the for loop. (Both methods result the same).
  • If the purpose of iteration is to get the keys of a dictionary, then we can call the `keys()` method on top of the dictionary which will return the sequence of the keys of the dictionary and so that can be used as the iterable object in the for loop.
  • Finally, if the purpose of iteration is to iterate through the keys and values of a dictionary object at the same time, then we can call the `items()` method of the target dictionary. This method returns a sequence that contains keys and values of the dictionary and so the result of this method can be used as the iterable object of the `for` loop.

Example: python loop through dictionary

employee = {
    "name":"John",
    "lastName":"Doe",
    "age":20,
    "email":"[email protected]"
}

print("Using the dictionary itself as the iterable object of the for loop:")
for value in employee:
    print(value)

print("Using the result of calling the values() method of the dictionary as the iterab object of the for loop:")
for value1 in employee:
    print(value1)

print("Using the result of calling the keys() method of the dictionary as the iterable object of the for loop:")
for key in employee:
    print(key)

print("using the result of calling the items() method of the dictionary as the iterable object of the for loop:")
for key,value in employee.items():
    print(f"The key is: {key} and the value is: {value}")

Output:

Using the dictionary itself as the iterable object of the for loop:

name

lastName

age

email

Using the result of calling the values() method of the dictionary as the iterab object of the for loop:

name

lastName

age

email

Using the result of calling the keys() method of the dictionary as the iterable object of the for loop:

name

lastName

age

email

using the result of calling the items() method of the dictionary as the iterable object of the for loop:

The key is: name and the value is: John

The key is: lastName and the value is: Doe

The key is: age and the value is: 20

The key is: email and the value is: [email protected]
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies