Looping through dictionary in python

Python — Loop Dictionaries

You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

Example

Print all key names in the dictionary, one by one:

Example

Print all values in the dictionary, one by one:

Example

You can also use the values() method to return values of a dictionary:

Example

You can use the keys() method to return the keys of a dictionary:

Читайте также:  Пробел между знаками html

Example

Loop through both keys and values, by using the items() method:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Python Iterate Over Dictionary – How to Loop Through a Dict

Shittu Olumide

Shittu Olumide

Python Iterate Over Dictionary – How to Loop Through a Dict

In this article, we will talk about dictionaries, and also learn how to loop through a dictionary in python.

Python Dictionaries

In Python, a dictionary is a built-in data structure used to store and organize data in key-value pairs.

A dictionary has two parts for each entry: a key and a value. The associated value can be accessed using the key, a special identifier. Any data type, including a number, string, list, or another dictionary, may be used as the value.

Dictionaries can be created by explicitly assigning values to keys or by using the dict() constructor function. They are indicated by curly braces < >. Here is an illustration of a basic dictionary:

In this example, the keys are ‘name’ , ‘age’ , and ‘city’ , and the corresponding values are ‘John’ , 25 , and ‘New Jersey’ , respectively.

We will now check out the different methods for looping through a dictionary: the items() method, the keys() method, the values() method, and using list comprehension.

How to Iterate Through a Dict Using the items() Method

We can use the items() method to loop through a dictionary and get both the key and value pairs.

DemoDict = # Loop through the dictionary for key, value in my_dict.items(): print(key, value) 
apple 1 banana 2 orange 3 

How to Iterate Through a Dict Using the keys() Method

If we only want to loop through the keys of the dictionary, we can use the keys() method.

DemoDict = # Loop through the keys of the dictionary for key in my_dict.keys(): print(key) 

How to Iterate Through a Dict Using the values() Method

Similarly, if we only want to loop through the values of the dictionary, we can use the values() method.

my_dict = # Loop through the values of the dictionary for value in my_dict.values(): print(value) 

How to Iterate Through a Dict Using List Comprehension

Finally, we can also use list comprehension to loop through a dictionary and get both the key and value pairs.

Let’s demonstrate this with an example:

my_dict = # Loop through the dictionary using list comprehension [(key, value) for key, value in my_dict.items()] 
[('apple', 1), ('banana', 2), ('orange', 3)] 

Note: The output of list comprehension is a list of tuples where each tuple contains a key-value pair of the dictionary.

Key Differences Between Methods of Looping Through a Dictionary in Python

Compatibility with different Python versions:

  • The items() method and values() method were introduced in Python 3, so they are not compatible with Python 2. If you need to write code that is compatible with both Python 2 and 3, you should use a basic for loop to iterate through the keys of the dictionary.
  • The keys() method is compatible with both Python 2 and 3, so it is a good option if you need to write code that works on both versions of Python.

Performance:

  • In general, using a basic for loop to iterate through the keys of a dictionary is the fastest method of looping through a dictionary in Python. This is because it avoids the overhead of creating a list of the dictionary’s keys or items.
  • The items() method is slower than a basic for loop because it creates a new list of tuples that contains the key-value pairs of the dictionary.
  • The values() method is also slower than a basic for loop because it creates a new list of the values of the dictionary.

Access to keys, values, or both:

  • When using a basic for loop to iterate through a dictionary, you only have access to the keys of the dictionary. To access the corresponding values, you need to use the keys as the index to the dictionary.
  • The items() method provides a way to access both the keys and values of the dictionary in a single loop. This is convenient when you need to work with both the keys and values of a dictionary.
  • The values() method, on the other hand, allows you to access only the values of the dictionary. This can be useful when you don’t need the keys but just want to work with the values themselves.

Conclusion

Dictionaries are incredibly useful for storing and retrieving data in a flexible and efficient manner. They are commonly used in Python programming for tasks such as data analysis, web development, and machine learning.

Let’s connect on Twitter and on LinkedIn. You can also subscribe to my YouTube channel.

Источник

Dictionary Iteration in Python – How to Iterate Over a Dict with a For Loop

Kolade Chris

Kolade Chris

Dictionary Iteration in Python – How to Iterate Over a Dict with a For Loop

In Python, a dictionary is one of the built-in data structures (the others are tuples, lists, and sets). A dictionary is a collection of key:value pairs and you can use them to solve various programming problems.

Dictionaries are very flexible to work with. You can get the keys and values separately, or even together.

This article is about looping over a dictionary with the for loop, but you can also loop through a dictionary with three methods:

  • the key() method: gets you the keys in a dictionary
  • the values() method: gets you the values in a dictionary
  • the items() method: gets you both the keys and values in a dictionary

In the example below, I use those 3 methods to get the keys, values, and items of the dictionary.

states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' ># Keys states_keys = states_tz_dict.keys() print(states_keys) # dict_keys(['Florida', 'Hawaii', 'Arizona', 'Colorado', 'Idaho', 'Texas', 'Washington', 'Wisconsin']) # Values tz_values = states_tz_dict.values() print(tz_values) # dict_values(['EST and CST', 'HST', 'DST', 'MST', 'MST and PST', 'CST and MST', 'PST', 'CST']) # Keys and values states_tz_dict_items = states_tz_dict.items() print(states_tz_dict_items) # dict_items([('Florida', 'EST and CST'), ('Hawaii', 'HST'), ('Arizona', 'DST'), ('Colorado', 'MST'), ('Idaho', 'MST and PST'), ('Texas', 'CST and MST'), ('Washington', 'PST'), ('Wisconsin', 'CST')]) 

That’s some iterations we did. But you can also loop through a dictionary with a for loop. That’s what we are going to look at in this tutorial.

What We’ll Cover

How to Iterate through a Dictionary with a for Loop

With the Python for loop, you can loop through dictionary keys, values, or items. You can also loop through the dictionary and put the key:value pair in a list of tuples. We are going to look at them one by one.

How to Iterate through Dictionary Keys with a for Loop

Remember how I got the keys of the dictionary with the keys() method in the first part of this article? You can use the same method in a for loop and assign each of the keys to a variable we can call k :

states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' >for k in states_tz_dict.keys(): print(k) # Result: # Florida # Hawaii # Arizona # Colorado # Idaho # Texas # Washington # Wisconsin 

How to Iterate through Dictionary Values with a for Loop

You can use the values() method in a for loop too, and assign the values to a variable you can call v :

states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' >for v in states_tz_dict.values(): print(v) # Result: # EST and CST # HST # DST # MST # MST and PST # CST and MST # PST # CST 

How to Iterate through Dictionary Items with a for Loop

The items() method comes in handy in getting the keys and values inside a for loop. This time around, you have to assign two variables instead of one:

states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' >for k, v in states_tz_dict.items(): print(k,"--->", v) # Result: # Florida ---> EST and CST # Hawaii ---> HST # Arizona ---> DST # Colorado ---> MST # Idaho ---> MST and PST # Texas ---> CST and MST # Washington ---> PST # Wisconsin ---> CST 

Note: You can use any letter for the variable(s) in a for loop. It doesn’t have to be k or v, or k, v.

How to Loop through a Dictionary and Convert it to a List of Tuples

To convert a dictionary to a list of tuples in Python, you still have to use the items() method inside a for loop.

But this time around, you have to surround the loop with square brackets. You also have to assign the loop to a separate variable and wrap the variable for both keys and values in brackets:

states_tz_dict = < 'Florida': 'EST and CST', 'Hawaii': 'HST', 'Arizona': 'DST', 'Colorado': 'MST', 'Idaho': 'MST and PST', 'Texas': 'CST and MST', 'Washington': 'PST', 'Wisconsin': 'CST' >list_of_tuples = [(k, v) for k, v in states_tz_dict.items()] print(list_of_tuples) # Result: [('Florida', 'EST and CST'), ('Hawaii', 'HST'), ('Arizona', 'DST'), ('Colorado', 'MST'), ('Idaho', 'MST and PST'), ('Texas', 'CST # and MST'), ('Washington', 'PST'), ('Wisconsin', 'CST')] 

Conclusion

In this tutorial, we looked at how to iterate through a dictionary with the for loop.

If you don’t want to use a for loop, you can also use any of the keys() , values() , or items() methods directly like I did in the first part of this article.

If you find this article helpful, don’t hesitate to share it on social media.

Kolade Chris

Kolade Chris

Web developer and technical writer focusing on frontend technologies. I also dabble in a lot of other technologies.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

Python Loop Through a Dictionary

You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.

Example

Print all key names in the dictionary, one by one:

Example

Print all values in the dictionary, one by one:

Example

You can also use the values() function to return values of a dictionary:

Example

Loop through both keys and values, by using the items() function:

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью