The Wayback Machine - https://web.archive.org/web/20241002105828/https://www.geeksforgeeks.org/python-dictionary-with-for-loop/
Open In App

Python Dictionary with For Loop

Last Updated : 02 Oct, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Combining dictionaries with for loops can be incredibly useful, allowing you to iterate over the keys, values, or both. In this article, we’ll explore Python dictionaries and how to work with them using for loops in Python.

Understanding Python Dictionaries

In this example, a person is a dictionary with three key-value pairs. The keys are “name,” “age,” and “city,” and the corresponding values are “John,” 30, and “New York,” respectively.

Python3




person = {"name": "John", "age": 30, "city": "New York"}
print(person)


Modifying Dictionary Elements While Iterating

Be cautious when modifying dictionary elements while iterating over them, as it can lead to unexpected results. If you need to make changes to the dictionary, consider creating a copy or collecting the changes in a separate list or dictionary.

  • Iterating Over Dictionary Keys
  • Iterating Over Dictionary Values
  • Iterating Over Both Keys and Values

Iterating Over Dictionary Keys

In this code, we use the keys() method to obtain a view of the dictionary’s keys, and then we iterate over these keys using a for loop.

Python3




# Iterating over dictionary keys
person = {"name": "John", "age": 30, "city": "New York"}
for key in person.keys():
    print(key)


Output

name
age
city

Iterating Over Dictionary Values

If you want to iterate over the values in a dictionary, you can use the values() method. Here’s how you can do it:

Python3




# Iterating over dictionary values
person = {"name": "John", "age": 30, "city": "New York"}
for value in person.values():
    print(value)


Output

John
30
New York

Iterating Over Both Keys and Values

Sometimes, you may need to iterate over both the keys and values simultaneously. To do this, you can use the items() method, which returns a list of key-value pairs as tuples.

Python3




# Iterating over dictionary key-value pairs
person = {"name": "John", "age": 30, "city": "New York"}
for key, value in person.items():
    print(key, ":", value)


Output

name : John
age : 30
city : New York


Similar Reads

Difference between for loop and while loop in Python
In this article, we will learn about the difference between for loop and a while loop in Python. In Python, there are two types of loops available which are 'for loop' and 'while loop'. The loop is a set of statements that are used to execute a set of statements more than one time. For example, if we want to print "Hello world" 100 times then we ha
4 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Using Else Conditional Statement With For loop in Python
Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated b
2 min read
Print first m multiples of n without using any loop in Python
Given n and m, print first m multiples of a m number without using any loops in Python. Examples: Input : n = 2, m = 3 Output : 2 4 6 Input : n = 3, m = 4 Output : 3 6 9 12 We can use range() function in Python to store the multiples in a range. First we store the numbers till m multiples using range() function in an array, and then print the array
3 min read
Python | Using for loop in Flask
Prerequisite: HTML Basics, Python Basics, Flask It is not possible to write front-end course every time user make changes in his/her profile. We use a template and it generates code according to the content. Flask is one of the web development frameworks written in Python. Through flask, a loop can be run in the HTML code using jinja template and a
3 min read
Understanding for-loop in Python
A Pythonic for-loop is very different from for-loops of other programming language. A for-loop in Python is used to loop over an iterator however in other languages, it is used to loop over a condition. In this article, we will take a deeper dive into Pythonic for-loop and witness the reason behind this dissimilarity. Let's begin by familiarizing o
6 min read
Do loop in Postgresql Using Psycopg2 Python
In this article, we use psycopg2 to loop through all data points using psycopg2 function in Python. We will first connect our PostgreSQL database using psycopg2.connect method, and pass the connection parameters such as the host, database, user, and password. Then we will create a cursor using the conn.cursor method. The cur.execute method, passes
4 min read
Python: Map VS For Loop
Map in Python : Map is used to compute a function for different values 'in a single line of code ' . It takes two arguments, first is function name, that is defined already and the other is list, tuple or any other iterables . It is a way of applying same function for multiple numbers . It generates a map object at a particular location . It works
3 min read
Ways to increment Iterator from inside the For loop in Python
For loops, in general, are used for sequential traversal. It falls under the category of definite iteration. Definite iterations mean the number of repetitions is specified explicitly in advance. But have you ever wondered, what happens, if you try to increment the value of the iterator from inside the for loop. Let's see with the help of the below
2 min read
Python Else Loop
Else with loop is used with both while and for loop. The else block is executed at the end of loop means when the given loop condition is false then the else block is executed. So let's see the example of while loop and for loop with else below. Else with While loop Consider the below example. C/C++ Code i=0 while i<5: i+=1 print("i ="
3 min read
Python VLC Instance – Setting Loop on the media
In this article we will see how we can set loop on the single media from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance object we can
2 min read
Unused variable in for loop in Python
Prerequisite: Python For loops The for loop has a loop variable that controls the iteration. Not all the loops utilize the loop variable inside the process carried out in the loop. Example: C/C++ Code # i,j - loop variable # loop-1 print("Using the loop variable inside :") # used loop variable for i in range(0, 5): x = (i+1)*2 print(x, en
3 min read
Python - Loop through files of certain extensions
A directory is capable of storing multiple files and python can support a mechanism to loop over them. In this article, we will see different methods to iterate over certain files in a given directory or subdirectory. Path containing different files: This will be used for all methods. Method 1: Using listdir() In this method, we will use the os.lis
4 min read
Convert a nested for loop to a map equivalent in Python
In this article, let us see how to convert a nested for loop to a map equivalent in python. A nested for loop's map equivalent does the same job as the for loop but in a single line. A map equivalent is more efficient than that of a nested for loop. A for loop can be stopped intermittently but the map function cannot be stopped in between. Syntax:
3 min read
Use for Loop That Loops Over a Sequence in Python
In this article, we are going to discuss how for loop is used to iterate over a sequence in Python. Python programming is very simple as it provides various methods and keywords that help programmers to implement the logic of code in fewer lines. Using for loop we can iterate a sequence of elements over an iterable like a tuple, list, dictionary, s
3 min read
Decrement in While Loop in Python
A loop is an iterative control structure capable of directing the flow of the program based on the authenticity of a condition. Such structures are required for the automation of tasks. There are 2 types of loops presenting the Python programming language, which are: for loopwhile loop This article will see how to decrement in while loop in Python.
3 min read
Why do Python lambda defined in a loop with different values all return the same result?
In this article, we are going to learn why Python lambda defined in a loop with different values all return the same result. In this article, we will explore the reasons behind this behavior and discuss how to avoid it. We will start by looking at how lambda functions are defined and executed, and how they capture the values of variables that are u
6 min read
Eliminating Loop from Python Code
In general, Loops are a pillar of any programming language. Loops allow us to execute a set of statements multiple times, which is particularly useful when dealing with lists, arrays, and kind of any of iterable. However, loops especially nested loops can slow down your code and affect the overall performance of your application. Eliminating Loop f
4 min read
How to Access Index in Python's for Loop
In this article, we will discuss how to access an index in Python for loop in Python. Here, we will be using 4 different methods of accessing the Python index of a list using for loop, including approaches to finding indexes in Python for strings, lists, etc. Python programming language supports the different types of loops, the loops can be execut
3 min read
Use For Loop to Iterate Tuple in Python
In this article, we will explore how to use a for loop to iterate through tuples in Python, along with some practical examples to illustrate its utility. Use For Loop to Iterate Tuple in PythonBelow are the ways by which we can use for loop to iterate Tuple in Python: Using Simple for loopTuple of TupleNested TuplesUsing enumerate functionsLoop thr
3 min read
Loop or Iterate over all or certain columns of a dataframe in Python-Pandas
Pandas DataFrames facilitate column-wise iteration, allowing convenient access to elements in each column. In this article, we will discuss how to loop or Iterate overall or certain columns of a DataFrame. Creating Pandas DataframeIn this article, we will use this Dataframe that we have created by using the Pandas package. C/C++ Code # import panda
5 min read
Loop through a JSON array in Python
A JSON array is an ordered list of values that can store multiple values such as string, number, boolean, or object. The values in a JSON array must be separated by commas and enclosed in squares in brackets []. In this article, we will learn how we can loop through a JSON array in Python. Iterate over a JSON object in PythonArrays in JSON are almo
4 min read
How to Decrement a Python for Loop
Python's for loop is a fundamental construct used for iterating over sequences. While Python does not have a built-in feature to decrement a loop index directly, there are multiple approaches to achieve this functionality. In this article, we'll explore different methods to decrement a for loop in Python, each with its advantages and use cases. Dec
2 min read
Run Code Alongside Python Tkinter'S Event Loop
Running code alongside Tkinter's event loop consists of integrating background tasks with Tkinter's main loop without freezing the user interface. This is essential for creating responsive applications that perform tasks such as updating the UI, handling network requests, or running computations concurrently. In this article, we will explore two di
2 min read
Python While Loop
Python While Loop is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the line immediately after the loop in the program is executed. Syntax of while loop in Pythonwhile expression: statement(s)Flowchart of Python While Loop While loop falls under the category of indefinite ite
9 min read
Sum Even and Odd Values with One For-Loop and No If-Condition Using Python
Summing even and odd numbers in a list is a common programming task. Typically, we'd use an if condition to check whether a number is even or odd. However, we can achieve this in Python efficiently using arithmetic operators and list slicing, without relying on if conditions. In this article, we'll explore how to sum even and odd values in Python u
4 min read
Python | Set 4 (Dictionary, Keywords in Python)
In the previous two articles (Set 2 and Set 3), we discussed the basics of python. In this article, we will learn more about python and feel the power of python. Dictionary in Python In python, the dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary. (
5 min read
Create a column using for loop in Pandas Dataframe
Adding a new column in an already created dataframe is quite easy. Adding a new column is actually required to process the data of dataframe created earlier. For that purpose, we can process the existing data and make a separate column to store the data. The simplest way to add a new column along with data is by creating a new column and assigning
3 min read
Create a pandas column using for loop
Let’s see how to create a column in pandas dataframe using for loop. Such operation is needed sometimes when we need to process the data of dataframe created earlier for that purpose, we need this type of computation so we can process the existing data and make a separate column to store the data. It can be easily done by for-loop. The data of colu
2 min read
for ... empty loop - Django Template Tags
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variable
3 min read