Table of Contents
#What is a dictionary in Python?
Define dictionary in Python
grammar
Method 1: Use for loop to iterate
Example
Output
Method 2: Use items() to iterate
Method 3: Use keys() to iterate
Method 4: Use values() to iterate
in conclusion
Home Backend Development Python Tutorial How to loop through a dictionary in Python?

How to loop through a dictionary in Python?

Sep 04, 2023 pm 04:57 PM
python cycle Traverse dictionary

How to loop through a dictionary in Python?

#What is a dictionary in Python?

Python is a programming language and one of the most popular object-oriented programming languages ​​that is built around dictionaries. A dictionary is described as a written mapping of multiple objects. Python dictionaries allow you to organize your data in a flexible way, storing key-value pairs in complex structures and accessing them by the same name.

Looking for a different way to iterate over a dictionary? This guide is for you. It covers looping over dictionaries using for loops, items(), keys(), and value() functions. Furthermore, it includes an illustrative example that demonstrates each method in action.

But before we delve into how Python iterates over dictionaries, let’s first see what the structure of a dictionary is in Python.

Define dictionary in Python

When using dictionaries in Python, you must consider the following considerations -

  • Dictionaries map keys to corresponding values ​​and arrange them into organized arrays.

  • The key must be immutable - that is, have an unchanged hash value throughout its lifetime.

So far, we know that dictionaries store data in key-value format. This means that each value is assigned a unique key that can be used to reference that specific value.

grammar

Let’s take a look at the syntax below,

d = {
   <key>: <value>,
   <key>: <value>,
      .
      .
      .
   <key>: <value>
}

A dictionary is constructed by enclosing a set of key-value combinations in curly braces ({}), with values ​​separated by commas. Dictionaries in Python use colon (:) to separate keys and values. Here d is defined for the dictionary.

Now consider that you want to create a program for a machine that displays a specific laptop's brand, Windows version, processor, and other relevant information. To achieve this, you need to iterate over the dictionary that stores this data so you can display it to the user of your program.

Look at the dictionary example in Python -

laptop = {
   'company': ‘HP',
   'windows_version': '11',
   ‘processor': Intel Core i7,
}

The words to the left of the colon are considered keys. In our example, company, windows_version, and processor are the keys.

Method 1: Use for loop to iterate

Dictionaries are iterable objects and can be used like any other object. Using a for loop to iterate over a dictionary is one of the simplest methods; this method allows you to access each value of the dictionary in turn.

Suppose you are writing a program for a laptop. You want to print the keys and values ​​of a specific laptop to the console, and each key-value pair should be printed to the console on a new line. How will you achieve this?

Example

Then, put the following code into the picture and witness the miracle!

laptop = {
   'company': 'HP',
   'windows_version': '11',
   'processor': 'Intel Core i7',
}

for key in laptop:
   print(key, laptop[key])

Output

The output returned by our code is -

company HP
windows_version 11
processor Intel Core i7
  • We started a variable called "laptop" which contains three pairs of keys and values.

  • This has been represented using the dictionary data type.

  • To display this information, we start a for loop that loops through each value and displays the key and its corresponding value to the console.

Method 2: Use items() to iterate

Using dictionary.items(), we can convert all key-value pairs of the dictionary into tuples. We can use a for loop and the items() method to iterate over everything in the list

Example

Let’s take the laptop dictionary as an example. To display our values ​​as a list of tuples we can use the following code snippet

laptop = {
   'company': 'HP',
   'windows_version': '11',
   'processor': 'Intel Core i7',
}
for i in laptop.items():
   print(i)

Output

Our code returns a list of tuples -

('company', 'HP')
('windows_version', '11')
('processor', 'Intel Core i7')
  • Through the for loop, we iterated through the laptop dictionary using items().

  • Each key-value pair will be converted into a tuple, which we can then use in a for loop.

  • Observe how each pair is printed to the console as a tuple. This method may be useful if you want to access each value in the dictionary as a tuple while iterating.

Method 3: Use keys() to iterate

Suppose our boss is interested in the information stored by an online store about his laptop, and we need to generate a list of keys stored in a dictionary. To achieve this goal, Python provides us with the convenient keys() method, which can extract all keys from a given dictionary.

Example

For this our code should look like this -

laptop = {
   'company': 'HP',
   'windows_version': '11',
   'processor': 'Intel Core i7',
}

for k in laptop.keys():
   print(k)

Output

Our code returns -

company
windows_version
processor
  • To illustrate this, we set up a for loop to pinpoint the keys stored in the dictionary.

  • Each key will be iterated and printed on the screen, with the results showing the three specified keys.

Method 4: Use values() to iterate

To access values ​​stored in a Python dictionary, you can use the values() method. Unlike keys(), this function iterates and returns each value present in the dictionary.

Example

The following code illustrates an example -

laptop = {
   'company': 'HP',
   'windows_version': '11',
   'processor': 'Intel Core i7',
}

for v in laptop.values():
   print(v)

Output

Our code returns -

HP
11
Intel Core i7
  • We have started a for loop to print the values ​​stored in the dictionary.

  • Values ​​are iterated, printed on the screen and displayed as the result.

in conclusion

You are right here! In this article, we explored several efficient ways to iterate over dictionaries in Python. We also implemented each method in the code. You're now ready to start iterating over Python dictionaries without breaking a sweat!

The above is the detailed content of How to loop through a dictionary in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are class methods in Python What are class methods in Python Aug 21, 2025 am 04:12 AM

ClassmethodsinPythonareboundtotheclassandnottoinstances,allowingthemtobecalledwithoutcreatinganobject.1.Theyaredefinedusingthe@classmethoddecoratorandtakeclsasthefirstparameter,referringtotheclassitself.2.Theycanaccessclassvariablesandarecommonlyused

python asyncio queue example python asyncio queue example Aug 21, 2025 am 02:13 AM

asyncio.Queue is a queue tool for secure communication between asynchronous tasks. 1. The producer adds data through awaitqueue.put(item), and the consumer uses awaitqueue.get() to obtain data; 2. For each item you process, you need to call queue.task_done() to wait for queue.join() to complete all tasks; 3. Use None as the end signal to notify the consumer to stop; 4. When multiple consumers, multiple end signals need to be sent or all tasks have been processed before canceling the task; 5. The queue supports setting maxsize limit capacity, put and get operations automatically suspend and do not block the event loop, and the program finally passes Canc

How to run a Python script and see the output in a separate panel in Sublime Text? How to run a Python script and see the output in a separate panel in Sublime Text? Aug 17, 2025 am 06:06 AM

ToseePythonoutputinaseparatepanelinSublimeText,usethebuilt-inbuildsystembysavingyourfilewitha.pyextensionandpressingCtrl B(orCmd B).2.EnsurethecorrectbuildsystemisselectedbygoingtoTools→BuildSystem→Pythonandconfirming"Python"ischecked.3.Ifn

How to use regular expressions with the re module in Python? How to use regular expressions with the re module in Python? Aug 22, 2025 am 07:07 AM

Regular expressions are implemented in Python through the re module for searching, matching and manipulating strings. 1. Use re.search() to find the first match in the entire string, re.match() only matches at the beginning of the string; 2. Use brackets() to capture the matching subgroups, which can be named to improve readability; 3. re.findall() returns all non-overlapping matches, and re.finditer() returns the iterator of the matching object; 4. re.sub() replaces the matching text and supports dynamic function replacement; 5. Common patterns include \d, \w, \s, etc., you can use re.IGNORECASE, re.MULTILINE, re.DOTALL, re

How to build and run Python in Sublime Text? How to build and run Python in Sublime Text? Aug 22, 2025 pm 03:37 PM

EnsurePythonisinstalledbyrunningpython--versionorpython3--versionintheterminal;ifnotinstalled,downloadfrompython.organdaddtoPATH.2.InSublimeText,gotoTools>BuildSystem>NewBuildSystem,replacecontentwith{"cmd":["python","-

How to use variables and data types in Python How to use variables and data types in Python Aug 20, 2025 am 02:07 AM

VariablesinPythonarecreatedbyassigningavalueusingthe=operator,anddatatypessuchasint,float,str,bool,andNoneTypedefinethekindofdatabeingstored,withPythonbeingdynamicallytypedsotypecheckingoccursatruntimeusingtype(),andwhilevariablescanbereassignedtodif

How to pass command-line arguments to a script in Python How to pass command-line arguments to a script in Python Aug 20, 2025 pm 01:50 PM

Usesys.argvforsimpleargumentaccess,whereargumentsaremanuallyhandledandnoautomaticvalidationorhelpisprovided.2.Useargparseforrobustinterfaces,asitsupportsautomatichelp,typechecking,optionalarguments,anddefaultvalues.3.argparseisrecommendedforcomplexsc

How to debug a remote Python application in VSCode How to debug a remote Python application in VSCode Aug 30, 2025 am 06:17 AM

To debug a remote Python application, you need to use debugpy and configure port forwarding and path mapping: First, install debugpy on the remote machine and modify the code to listen to port 5678, forward the remote port to the local area through the SSH tunnel, then configure "AttachtoRemotePython" in VSCode's launch.json and correctly set the localRoot and remoteRoot path mappings. Finally, start the application and connect to the debugger to realize remote breakpoint debugging, variable checking and code stepping. The entire process depends on debugpy, secure port forwarding and precise path matching.

See all articles