How To Loop and Iterate Over Python Dictionary? – POFTUT

How To Loop and Iterate Over Python Dictionary?


Dictionaries provide simple data types with value and key. Dictionary data may be used in an iteration with for loop. By using for mechanism we can iterate over dictionary elements easily. In this tutorial, we will look at 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

Iterate with Implicit Iterator

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

for x in mydict: 
  print(x)
Iterate with Iterator 
Iterate with Iterator 

Iterate with Keys

Like the previous example, we can specify the iterate keys with keys() function of the dictionary. keys() function will return all keys inside the 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 Keys and Values 

Iterate Only Values

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

for v in mydict.values():     
  print(v)
Iterate Only Values
Iterate Only Values

LEARN MORE  How To Create Nested For Loops In Python?

1 thought on “How To Loop and Iterate Over Python Dictionary?”

Leave a Comment