Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How do you Loop Through a Dictionary in Python?
Python dictionaries store data in key-value pairs and are one of the most commonly used data structures. When working with dictionaries, you'll often need to loop through them to access or process their contents. Python provides several methods to iterate through dictionaries effectively.
What is a Dictionary in Python?
A dictionary in Python is a collection of key-value pairs where each key is unique and immutable. Dictionaries are mutable, ordered (as of Python 3.7+), and allow fast lookups by key.
Syntax
dictionary = {
key1: value1,
key2: value2,
key3: value3
}
Here's an example dictionary representing laptop specifications ?
laptop = {
'company': 'HP',
'windows_version': '11',
'processor': 'Intel Core i7'
}
print(laptop)
{'company': 'HP', 'windows_version': '11', 'processor': 'Intel Core i7'}
Method 1: Using for Loop (Keys Only)
The simplest way to iterate through a dictionary is using a for loop. By default, this loops through the keys ?
laptop = {
'company': 'HP',
'windows_version': '11',
'processor': 'Intel Core i7'
}
for key in laptop:
print(key, laptop[key])
company HP windows_version 11 processor Intel Core i7
Method 2: Using items() Method
The items() method returns key-value pairs as tuples, allowing you to access both simultaneously ?
laptop = {
'company': 'HP',
'windows_version': '11',
'processor': 'Intel Core i7'
}
for key, value in laptop.items():
print(f"{key}: {value}")
company: HP windows_version: 11 processor: Intel Core i7
Method 3: Using keys() Method
The keys() method explicitly returns only the dictionary keys ?
laptop = {
'company': 'HP',
'windows_version': '11',
'processor': 'Intel Core i7'
}
for key in laptop.keys():
print(key)
company windows_version processor
Method 4: Using values() Method
The values() method returns only the dictionary values ?
laptop = {
'company': 'HP',
'windows_version': '11',
'processor': 'Intel Core i7'
}
for value in laptop.values():
print(value)
HP 11 Intel Core i7
Comparison of Methods
| Method | Returns | Best For |
|---|---|---|
for key in dict |
Keys only | When you need to access keys and values separately |
dict.items() |
Key-value pairs | When you need both keys and values together |
dict.keys() |
Keys only | When you only need the keys |
dict.values() |
Values only | When you only need the values |
Conclusion
Python provides multiple ways to iterate through dictionaries. Use items() when you need both keys and values, keys() for keys only, and values() for values only. The simple for loop is equivalent to using keys() but requires dictionary indexing to access values.
