How to Iterate Python Dictionary ? - onlinetutorialspoint

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
Python dictionary stores the data in a key-value pair format, it allows the developers to store a large amount/variety of data; therefore, there were several ways to iterate over them. In this tutorials, we are going to see how to Iterate over dictionary Python in different ways.
As a dictionary stores the data as key-value pair, it allows us to loop through the keys or values.
The following dictionary consists of persons information such as user_name,first_name and last_name. Lets try to iterate this.
persons = {
    'user_name':'chandra',
    'first_name':'chandra shekhar',
    'last_name':'goka'
}
We could loop through dictionary using a for loop like below.
persons = {
    'user_name':'chandra',
    'first_name':'chandra shekhar',
    'last_name':'goka'
}

#Looping thorough key,values
for key,value in persons.items():
    print(f"Key: {key} - Value: {value}")
On the above for loop we created names for the two variables key and value (you can choose any names for these). items() method returns the key-value pair for a specific iteration and the the loop assigns key-values into the key,value variables for the each iteration.
Output:
Key: user_name - Value: chandra
Key: first_name - Value: chandra shekhar
Key: last_name - Value: goka
The key() method is used to get the key from a dictionary, using which we can loop though the keys. The below dictionary is a collection of favorite subject of each person. Lets loop though this Dictionary using keys.
favorite_subjects={
    'chandra':'Computers',
    'panvith':'Physics',
    'jon':'Mathematics',
    'robert':'Computers'
}

for name,fav_subject in favorite_subjects.items():
    print(f"{name} likes {fav_subject}")
Output:
chandra
panvith
jon
robert
From Python 3.7 looping through a dictionary gives the items the same way the items were inserted. If you would like to read the items in an sorted order, we can do this by applying sorted() method on it.
favorite_subjects={
    'chandra':'Computers',
    'panvith':'Physics',
    'jon':'Mathematics',
    'robert':'Computers'
}

#Keys in Order
for name in sorted(favorite_subjects.keys()):
    print(name)
Output:
chandra
jon
panvith
robert
Just like loop though the keys, we can also loop through the values of a dictionary using values() method.
favorite_subjects={
    'chandra':'Computers',
    'panvith':'Physics',
    'jon':'Mathematics',
    'robert':'Computers'
}
for fav_subject in favorite_subjects.values():
    print(fav_subject)
Output:
Computers
Physics
Mathematics
Computers
favorite_subjects= {
    'chandra':'Computers',
    'panvith':'Physics',
    'jon':'Mathematics',
    'robert':'Computers'
}

#Values in Order
for fav_subject in sorted(favorite_subjects.values()):
    print(fav_subject)
Output:
Computers
Computers
Mathematics
Physics
As you can see on the above output, there was a duplicate subject (Computer), we can remove the duplicates while iterating the dictionary values like below.
Using set() method we can remove the duplicates – You can see more about set function here.
favorite_subjects= {
    'chandra':'Computers',
    'panvith':'Physics',
    'jon':'Mathematics',
    'robert':'Computers'
}

#Remove duplicates in values
for fav_subject in sorted(set(favorite_subjects.values())):
    print(fav_subject)
Output:
Computers
Mathematics
Physics
Python Set data structure in depth
Python dictionary
Happy Learning 🙂

Python Dictionary Methods and Usages
How to sort python dictionary by key ?
Python – How to remove key from dictionary ?
Python – How to merge two dict in Python ?
How to read JSON file in Python ?
How to create Python Iterable class ?
How to access for loop index in Python
5 Ways to Iterate ArrayList in Java
What are Python default function parameters ?
What are different Python Data Types
Python raw_input read input from keyboard
Python How to read input from keyboard
Python Tuple Data Structure in Depth
What are the different ways to Sort Objects in Python ?
Python List Data Structure In Depth

Python Dictionary Methods and Usages
How to sort python dictionary by key ?
Python – How to remove key from dictionary ?
Python – How to merge two dict in Python ?
How to read JSON file in Python ?
How to create Python Iterable class ?
How to access for loop index in Python
5 Ways to Iterate ArrayList in Java
What are Python default function parameters ?
What are different Python Data Types
Python raw_input read input from keyboard
Python How to read input from keyboard
Python Tuple Data Structure in Depth
What are the different ways to Sort Objects in Python ?
Python List Data Structure In Depth
 


Δ
 Python – Introduction
 Python – Features
 Python – Install on Windows
 Python – Modes of Program
 Python – Number System
 Python – Identifiers
 Python – Operators
 Python – Ternary Operator
 Python – Command Line Arguments
 Python – Keywords
 Python – Data Types
 Python – Upgrade Python PIP
 Python – Virtual Environment
 Pyhton – Type Casting
 Python – String to Int
 Python – Conditional Statements
 Python – if statement
 Python – *args and **kwargs
 Python – Date Formatting
 Python – Read input from keyboard
 Python – raw_input
 Python – List In Depth
 Python – List Comprehension
 Python – Set in Depth
 Python – Dictionary in Depth
 Python – Tuple in Depth
 Python – Stack Datastructure
 Python – Classes and Objects
 Python – Constructors
 Python – Object Introspection
 Python – Inheritance
 Python – Decorators
 Python – Serialization with Pickle
 Python – Exceptions Handling
 Python – User defined Exceptions
 Python – Multiprocessing
 Python – Default function parameters
 Python – Lambdas Functions
 Python – NumPy Library
 Python – MySQL Connector
 Python – MySQL Create Database
 Python – MySQL Read Data
 Python – MySQL Insert Data
 Python – MySQL Update Records
 Python – MySQL Delete Records
 Python – String Case Conversion
 Howto – Find biggest of 2 numbers
 Howto – Remove duplicates from List
 Howto – Convert any Number to Binary
 Howto  – Merge two Lists
 Howto – Merge two dicts
 Howto – Get Characters Count in a File
 Howto – Get Words Count in a File
 Howto – Remove Spaces from String
 Howto –  Read Env variables
 Howto – Read a text File
 Howto – Read a JSON File
 Howto –  Read Config.ini files
 Howto – Iterate Dictionary
 Howto – Convert List Of Objects to CSV
 Howto – Merge two dict in Python
 Howto – create Zip File
 Howto – Get OS info
 Howto – Get size of Directory
 Howto – Check whether a file exists
 Howto –  Remove key from dictionary
 Howto – Sort Objects
 Howto – Create or Delete Directories
 Howto – Read CSV File
 Howto – Create Python Iterable class
 Howto – Access for loop index
 Howto – Clear all elements from List
 Howto – Remove empty lists from a List
 Howto – Remove special characters from String
 Howto – Sort dictionary by key
 Howto – Filter a list