search
HomeBackend DevelopmentPython TutorialHow to loop through a dictionary in Python?

How to loop through a dictionary in Python?

Sep 04, 2023 pm 04:57 PM
pythoncycleTraverse 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
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment