How To Loop and Iterate Over Python Dictionary?

Dictionaries provides simple data types with value and key. Dictionary data may be used in an iteration with for loop. By using for we can iterate over dictionary elements easily. In this tutorial we will look different ways to iterate over dictionary elements.

Example Dictionary

We will use following dictionary type named mydict in this tutorial.

mydict={'b': 2, 'a': 1, 'c': 3}

Example Dictionary

Iterate with Implicit Iterator

Python dictionary type provides iterator interface where it can be consumed by for loops. We just need to provide the dictionary in for loop. This is shorter implementation of iterate with keys where we do not need to call iterkeys . In this example we will iterate over with keys in mydict dictionary.

for x in mydict:
print(x)

Iterate with Iterator

Iterate with Keys

Like previous example we can specify the iterate keys with keys() function of dictionary. keys() function will return all keys inside given dictionary as python list than this list will be iterated with for loop.

for x in mydict.keys():
print(x)

Iterate Keys and Values

We can use functions provided by dictionary data type which will populate both keys and dictionaries in the same step of for loop. We will use items() function which will populate key and value in the same step. We will populate keys into k variable and values into v variable in each step.

for k,v in mydict.items():
print(k)
print(v)

Iterate Keys and Values

Iterate Only Values

We can only iterate over values without using any key. We will use values() function provided by dictionary type which will populate values in given dictionary in an iterable format. We will put values of dictionary in each step into variable v .