AppDividend
Latest Code Tutorials

Different Ways to Iterate Over Dictionary in Python

0

Python Dictionaries map keys to values and store them in the collection or an array. Dictionary is An associative array, where arbitrary keys are mapped to values. Dictionaries are iterables that support element access using integer indices, keys index dictionaries. The Dictionary keys can be any object with __hash__() and __eq__() functions.

In Python 3.6 and above that version, the keys and values of the Dictionary are iterated over in exact same order in which they were created. When it comes to iterating over a Dictionary, Python language provides you with some great methods and functions that we will cover in this post.

Different Ways to Iterate Over Dictionary

There are mainly four ways to iterate over the Dictionary in Python.

  1. Iterating through .items()
  2. Iterating over .keys()
  3. Iterating over .values()
  4. Iterating through keys directly

Let’s discuss all the approaches one by one.

Iterating a Dictionary through .items()

The items() method returns a view object that displays a list of Dictionary’s (key, value) tuple pairs.

Syntax

dictionary.items()

Example

data = {
    'name': 'Obama',
    'position': 'Former President'
}

print(data.items())

Output

dict_items([('name', 'Obama'), ('position', 'Former President')])

Views can be iterated over to yield with their respective data, so you can iterate over a dictionary in Python by using a view object returned by the .items().

Let’s iterate the dict_items() object with the for loop.

data = {
    'name': 'Obama',
    'position': 'Former President'
}

data_items = data.items()

for item in data_items:
    print(item)

Output

('name', 'Obama')
('position', 'Former President')

The view object returned by .items() method yields the key-value pairs one at a time and allows us to iterate through a dictionary in Python, but in such a way that you can access the keys and values at the same time. 

If you take a look at the individual items yielded by the .items() method, you will notice that they’re tuple objects. Now, you can unpack the tuple to iterate through the keys and values of the Dictionary.

See the following code.

data = {
    'name': 'Obama',
    'position': 'Former President'
}

data_items = data.items()

for key, value in data_items:
    print(key, '=>', value)

Output

name => Obama
position => Former President

Every time the for loop runs, the key variable will store the key, and the value variable will store the value of the element that has been processed one at a time. With this approach, you will have more control over the items of the Dictionary, and you will be able to process the keys and values pythonic way.

Let’s head to the second way to iterate Python dictionary.

Iterating Over .keys()

The keys() method returns a view object that displays the list of all the keys of the Dictionary. If you just need to work with dictionary keys, then you can use the dict.keys() method, which returns the new view object containing the Dictionary’s keys.

Syntax

dictionary.keys()

Example

data = {
    'name': 'Obama',
    'position': 'Former President'
}

data_keys = data.keys()
print(data_keys)

Output

dict_keys(['name', 'position'])

The data_keys object returned by .keys() here provided a dynamic view on the keys of the data dictionary. The data_keys view can be used to iterate through the keys of data. To iterate over a Dictionary in Python by using .keys(), you just need to call .keys() in the header of a for loop.

data = {
    'name': 'Obama',
    'position': 'Former President'
}

data_keys = data.keys()

for key in data_keys:
    print(key)

Output

name
position

When you call .keys() on a data dictionary, you get a view of keys. Python knows that view objects are iterators, so it starts looping, and you can process the keys of data.

Now, what about values, how can we get the values of the Dictionary?

Well, the answer to the question is: indexing operator( [ ] ).

You can access the values of the Dictionary using the indexing operator. See the below code.

data = {
    'name': 'Obama',
    'position': 'Former President'
}

data_keys = data.keys()

for key in data_keys:
    print(key, '=>', data[key])

Output

name => Obama
position => Former President

This way, you’ve got access to the keys (key) and values (data[key]) of the data dictionary at the same time, and you will be able to perform any operations on them.

Iterating over .values() in Python Dictionary

The values() method returns a view object that displays a list of all the values in the Dictionary. Till now, we have seen dict.items() and dict.keys() method to iterate the Dictionary. The next method is for iterating the values() of the Dictionary.

Syntax

dictionary.values()

Example

data = {
    'name': 'Obama',
    'position': 'Former President'
}

data_values = data.values()
print(data_values)

Output

dict_values(['Obama', 'Former President'])

The data_values object returned by .values() here provided a dynamic view on the keys of the data dictionary. The data_values view can be used to iterate through the values of data. To iterate over a dictionary in Python by using .keys(), you just need to call .values() in the header of a for loop.

data = {
    'name': 'Obama',
    'position': 'Former President'
}

data_values = data.values()

for value in data_values:
    print(value)

Output

Obama
Former President

Using .values() method, you will be getting access to only the values of the data, without dealing with the keys. 

Iterating through direct keys and []

If you don’t want to use dict.keys() and dict.values() method and still want to iterate the keys and values in Python directly, and then we can still do that.

Python’s dictionaries are the mapping objects. That means that they inherit some special methods, which Python uses internally to calculate some operations. These methods are named using a naming convention of adding the double underscore at the beginning of and at the end of the function’s name.

For mappings (like dictionaries), The __iter__() should iterate over the keys. That means that if you put a dictionary directly into the for loop, Python will automatically call the .__iter__() on that Dictionary, and you will get an iterator over its keys. Then we used the conventional ways of getting the value of the Dictionary using an indexing operator.

See the following code.

data = {
    'name': 'Obama',
    'position': 'Former President'
}

for key in data:
  print(key, '=>', data[key])

Output

name => Obama
position => Former President

The above code allows us to get access to the keys (key) and the values (data[key]) of the data dictionary at the same time. With this approach, you can do any operation with both the keys and the values.

This is the by far one of the most simplest way to iterate through the dictionary in Python. Just put it directly into the for loop, and you’re done!

Python in operator to check an item in Dictionary

You can use the support membership tests(in operator), which is an essential operator if you’re trying to know if the particular item is in a Dictionary or not.

data = {
    'name': 'Obama',
    'position': 'Former President'
}

print('name' in data.keys())
print('Obama' in data.values())

print('age' in data.keys())
print(73 in data.values())

Output

True
True
False
False

The membership test using in operator returns True if the key (or value or item) is present in the Dictionary you are testing, and returns False otherwise.

This membership test allows us to not iterate through a Dictionary in Python if you just want to know if the certain key (or value or item) is present in a Dictionary or not.

Conclusion

You now know how to iterate through a dictionary in Python using various approaches. This will help us to be more efficient and effective in your use of dictionary iteration in the future.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.