Python - Loop Dictionaries



Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the items do not have a positional index. However, traversing a dictionary is still possible with different techniques.

Loop Through Dictionary Keys using For Loop

Running a simple for loop over the dictionary object traverses the keys used in it.

Example

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers:
   print (x)

It will produce the following output

10
20
30
40

Loop Through Dictionary Keys and Values using For Loop

Once we are able to get the key, its associated value can be easily accessed either by using square brackets operator or with get() method.

Example

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers:
   print (x,":",numbers[x])

It will produce the following output

10 : Ten
20 : Twenty
30 : Thirty
40 : Forty

Loop Through a Dictionary using Built-in Methods

The items(), keys() and values() methods of dict class return the view objects dict_items, dict_keys and dict_values respectively. These objects are iterators, and hence we can run a for loop over them.

The dict_items object is a list of key-value tuples over which a for loop can be run as follows:

Example: Loop Through Dictionary Items

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers.items():
   print (x)

It will produce the following output

(10, 'Ten')
(20, 'Twenty')
(30, 'Thirty')
(40, 'Forty')

Here, "x" is the tuple element from the dict_items iterator. We can further unpack this tuple in two different variables.

Example: Loop Through Dictionary Keys, Values

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x,y in numbers.items():
   print (x,":", y)

It will produce the following output

10 : Ten
20 : Twenty
30 : Thirty
40 : Forty

Example: Loop Through Dictionary Keys

Similarly, the collection of keys in dict_keys object can be iterated over.

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers.keys():
   print (x, ":", numbers[x])

It will produce the following output

10 : Ten
20 : Twenty
30 : Thirty
40 : Forty

Respective Keys and values in dict_keys and dict_values are at same index. In the following example, we have a for loop that runs from 0 to the length of the dict, and use the looping variable as index and print key and its corresponding value.

Example: Loop Through Dictionary Using keys() and values()

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
l = len(numbers)
for x in range(l):
   print (list(numbers.keys())[x], ":", list(numbers.values())[x])

It will produce the following output

10 : Ten
20 : Twenty
30 : Thirty
40 : Forty
Advertisements