How to iterate through a dictionary in Python?

PythonServer Side ProgrammingProgramming

There are two ways of iterating through a Python dictionary object. One is to fetch associated value for each key in keys() list.

>>> D1 = {1:'a', 2:'b', 3:'c'} 
>>> for k in D1.keys():
   print (k, D1[k])
1 a
2 b
3 c

There is also items() method of dictionary object which returns list of tuples, each tuple having key and value. Each tuple is then unpacked to two variables to print one dictionary item at a time.

>>> D1={1:'a', 2:'b', 3:'c'} 
>>> for k, v in D1.items():
   print (k, v)
1 a
2 b
3 c
raja
Published on 28-Dec-2017 10:19:04
Advertisements