
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Iterate Over Dictionaries Using For Loops in Python
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
Advertisements