How to iterate over dictionaries using 'for' loops in Python?

PythonServer Side ProgrammingProgramming

Even though dictionary itself is not an iterable object, the items(), keys() and values methods return iterable view objects which can be used to iterate through dictionary.

The items() method returns a list of tuples, each tuple being key and value pair.

>>> d1={'name': 'Ravi', 'age': 23, 'marks': 56}
>>> for t in d1.items():
print (t)

('name', 'Ravi')
('age', 23)
('marks', 56)

Key and value out of each pair can be separately stored in two variables and traversed like this −

>>> d1={'name': 'Ravi', 'age': 23, 'marks': 56}
>>> for k,v in d1.items():
print (k,v)

name Ravi
age 23
marks 56

Using iterable of keys() method each key and associated value can be obtained as follows −

>>> for k in d1.keys():
print (k, d1.get(k))

name Ravi
age 23
marks 56
raja
Published on 22-Feb-2018 10:53:26
Advertisements