Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python | Filter Tuple Dictionary Keys
Next article icon

Python Iterate Dictionary Key, Value

Last Updated : 19 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dictionary must be unique however, we can assign the same values to different keys.

In this article, we are going to cover some basic to advanced ways of iterating over a dictionary's keys and values in Python. We will be covering all the methods to iterate Dictionary keys and values with clear and concise examples.

Syntax

d = {'key1':'value1','key2':'value2',..............}

Note : { } is used in the case of Python's Set as well as Python's Dictionary.

Iterate Dictionary's Key, Value

Let's discuss some of the common as well as efficient methods to iterate dictionary key, and value.

  • Using Iteration Method
  • Using .items() Function
  • Using .keys() and .values()

Python Dictionary Key-Value Using Iteration

In this method, we will simply iterate over dictionary keys and retrieve their corresponding values. Below, Python code defines a function `dict_iter` that iterates over the keys of a dictionary and then demonstrates its usage on a specific dictionary.

Python3
#function to iterate over each keys and its #corresponding values def dict_iter(d):        for i in d:         print('KEYS: {} and VALUES: {}'.format(i,d[i]))          #Main Function if __name__ == "__main__":     d = {"Vishu":1,"Aayush":2,"Neeraj":3,"Sumit":4}          #calling function created above     dict_iter(d) 

Output
KEYS: Vishu and VALUES: 1 KEYS: Aayush and VALUES: 2 KEYS: Neeraj and VALUES: 3 KEYS: Sumit and VALUES: 4

Python Dictionary Key-Value Using .items()

In this example we will be using Python's dictionary function .items() . This function will return a list consists of dictionary's key and values. In below code , function `dict_iter` iterates over the keys and values of a dictionary, printing each key-value pair along with the dictionary items.

Python3
#function to iterate over each keys and its #corresponding values def dict_iter(d):          for i,j in d.items():         print('KEYS: {} and VALUES: {}'.format(i,j))              #.items()     print("\n")     print(d.items())                   #Main Function         if __name__ == "__main__":     d = {"Vishu": 1,"Aayush":2,"Neeraj":3,"Sumit":4}                   #calling function created above     dict_iter(d) 

Output
KEYS: Vishu and VALUES: 1 KEYS: Aayush and VALUES: 2 KEYS: Neeraj and VALUES: 3 KEYS: Sumit and VALUES: 4   dict_items([('Vishu', 1), ('Aayush', 2), ('Neeraj', 3), ('Sumit', 4)])

Iterate Dictionary Key, Value Using .keys() and .values()

In this example, we are going to use Python dictionary's two most useful methods i.e. .keys() and .values(). We are using these methods to iterate over keys and values of dictionaries separately. In below code , function `dict_iter` iterates over the keys and values of a dictionary separately.

Python3
#function to iterate over each keys and its #corresponding values def dict_iter(d):          #iterating over keys and values separately.     for i in d.keys():         print('KEYS: ',i)     for i in d.values():         print('VALUES: ',i)  #Main Function if __name__ == "__main__":     d = {"Vishu":1,"Aayush":2,"Neeraj":3,"Sumit":4}                   #calling function created above     dict_iter(d) 

Output
KEYS:  Vishu KEYS:  Aayush KEYS:  Neeraj KEYS:  Sumit VALUES:  1 VALUES:  2 VALUES:  3 VALUES:  4

Conclusion

In Python, Dictionary is a data structure used to store data in form of key value pairs. Each created keys of a dictionary must be unique however we can duplicate the value part. Dictionary is a mutable ( which means once created we modify or update its value later on) and unordered collection of data. We can created a dictionary with dict() or with the help of curly braces.


Next Article
Python | Filter Tuple Dictionary Keys

V

vishuvaishnav3001
Improve
Article Tags :
  • Python Programs
  • Geeks Premier League
  • Geeks Premier League 2023

Similar Reads

  • Get Dictionary Value by Key - Python
    We are given a dictionary and our task is to retrieve the value associated with a given key. However, if the key is not present in the dictionary we need to handle this gracefully to avoid errors. For example, consider the dictionary : d = {'name': 'Alice', 'age': 25, 'city': 'New York'} if we try t
    3 min read
  • Python | Filter Tuple Dictionary Keys
    Sometimes, while working with Python dictionaries, we can have it’s keys in form of tuples. A tuple can have many elements in it and sometimes, it can be essential to get them. If they are a part of a dictionary keys and we desire to get filtered tuple key elements, we need to perform certain functi
    4 min read
  • Inverse Dictionary Values List - Python
    We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]} Using defau
    2 min read
  • Iterate Through Dictionary Keys And Values In Python
    In Python, a Dictionary is a data structure where the data will be in the form of key and value pairs. So, to work with dictionaries we need to know how we can iterate through the keys and values. In this article, we will explore different approaches to iterate through keys and values in a Dictionar
    2 min read
  • Python - Iterate over Tuples in Dictionary
    In this article, we will discuss how to Iterate over Tuples in Dictionary in Python. Method 1: Using index We can get the particular tuples by using an index: Syntax: dictionary_name[index] To iterate the entire tuple values in a particular index for i in range(0, len(dictionary_name[index])): print
    2 min read
  • Python | Iterate through value lists dictionary
    While working with dictionary, we can have a case in which we need to iterate through the lists, which are in the keys of dictionaries. This kind of problem can occur in web development domain. Let's discuss certain ways in which this problem can be solved. Method #1: Using list comprehension List c
    4 min read
  • Python - Value length dictionary
    Sometimes, while working with a Python dictionary, we can have problems in which we need to map the value of the dictionary to its length. This kind of application can come in many domains including web development and day-day programming. Let us discuss certain ways in which this task can be perfor
    4 min read
  • Python | Extract filtered Dictionary Values
    While working with Python dictionaries, there can be cases in which we are just concerned about getting the filtered values list and don’t care about keys. This is yet another essential utility and solution to it should be known and discussed. Let’s perform this task through certain methods. Method
    4 min read
  • Minimum Value Keys in Dictionary - Python
    We are given a dictionary and need to find all the keys that have the minimum value among all key-value pairs. The goal is to identify the smallest value in the dictionary and then collect every key that matches it. For example, in {'a': 3, 'b': 1, 'c': 2, 'd': 1}, the minimum value is 1, so the res
    4 min read
  • Python - Print dictionary of list values
    In this article, we will explore various ways on How to Print Dictionary in Python of list values. A dictionary of list values means a dictionary contains values as a list of dictionaries in Python. Example: {'key1': [{'key1': value,......,'key n': value}........{'key1': value,......,'key n': value}
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences