
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to 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
- Related Articles
- How to Iterate over Tuples in Dictionary using Python
- Iterate over a dictionary in Python
- Iterate over a list in Python
- Iterate over a set in Python
- Python program to iterate over multiple lists simultaneously?
- How to iterate over a Hashmap in Kotlin?
- How to iterate over a list in Java?
- How to make loops run faster using Python?
- Iterate over characters of a string in Python
- How to iterate over all MongoDB databases?
- How to iterate over a Java list?
- How to iterate over a C# dictionary?
- How to iterate over a C# list?
- How to iterate over a C# tuple?
- Java Program to Iterate over ArrayList using Lambda Expression

Advertisements