How to Iterate Through a List in Python

The items() method, the keys() method, and the values() method return values you can use to iterate through a dictionary in Python. items() returns both the keys and values in a Python dictionary. keys() returns the keys in a dictionary. values() returns the values in a dictionary. You can also use a for loop to iterate through a Python dictionary.

form-submission

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Get exclusive scholarships and prep courses

form-submission

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Get exclusive scholarships and prep courses

When you're working with dictionaries, you may want to iterate through the values you have stored.

For instance, say you're creating a program for a librarian that shows a specific book's title, description, author, and other relevant information. You would want to iterate through the dictionary storing that data so you can display it to the user of your profgram.

There are a few ways you can iterate through a dictionary. This tutorial will discuss how to iterate through a dictionary using a for loop, items(), and keys(). We'll also explore an example of each of these approaches being used to iterate through a dictionary.

Dictionary Refresher

Python dictionaries store data in a key-value structure. This means that each value is assigned a key that can be used to reference that particular value.

Here's an example of a dictionary in Python:

book = { 	'title': 'The Great Gatsby', 	'author': 'F. Scott Fitzgerald', 	'date_ published': 1925, 	'in_stock': True }

Our dictionary uses colons (:) throughout, which separate our keys and values. The words on the left of the colons are the keys, which in this case are title, author, date_published, and in_stock. These keys are all formatted as strings.

Python Iterate Through Dictionary

You can iterate through a Python dictionary using the keys(), items(), and values() methods. keys() returns an iterable list of dictionary keys. items() returns the key-value pairs in a dictionary. values() returns the dictionary values. You can also use a for loop to iterate over a dictionary.

81% of participants stated they felt more confident about their tech job prospects after attending a bootcamp. Get matched to a bootcamp today.

The average bootcamp grad spent less than six months in career transition, from starting a bootcamp to finding their first job.

Say wanted to know how many books your library had in stock. You may want to iterate through every dictionary to calculate the total of each book's quantity.

Iterate Using for Loop

Dictionaries are iterable objects, which means you can iterate through them like any other object. Perhaps the simplest way to iterate through a dictionary is to use a Python for loop. This loop allows you to run through each value in the dictionary individually.

Let's say you are writing a program for a librarian. You want to print out the keys and values of a specific book to the console. Each key-value pair should be printed to the console on a new line. You could accomplish this task using the following code:

book = { 	'title': 'The Great Gatsby', 	'author': 'F. Scott Fitzgerald', 	'date_ published': 1925, 	'in_stock': True }  for key in book: 	print(key, book[key])

Our code returns the following:

title The Great Gatsby author F. Scott Fitzgerald date_ published 1925 in_stock True

To start, we declare a Python variable called book which stores four keys and values. This variable stores a value in the dictionary data type.

Then, we declare a for loop that iterates through each value in our dictionary. The for loop prints out both the key and the value associated with that key to the console.

Iterate Using items()

dictionary.items() converts each key-value pair in a dictionary into a tuple. Using a for loop and the items() method you can iterate over all of the keys and values in a list.

form-submission

Find Your Bootcamp Match

  • Career Karma matches you with top tech bootcamps
  • Get exclusive scholarships and prep courses

Let's say that we still want to iterate through our book dictionary. But we want our values to appear as a list of tuples. We could do so using the following code:

for i in book.items(): 	print(i)

Our code returns a list of tuples:

('title', 'The Great Gatsby') ('author', 'F. Scott Fitzgerald') ('date_ published', 1925) ('in_stock', True)

We define a for loop that iterates through our book dictionary using items(). items() converts each key-value pair into a tuple, which we can then access in our for loop. As you can see, each key-value pair was printed to the console as a tuple.

This approach can be useful if you want to convert each value in your dictionary to a tuple while you are iterating.

Iterate Using keys()

Often, you may only want to iterate through the keys of a dictionary.

The librarian with whom we are working has asked us to compile a list of the information the library stores on each book. In our terms, this means the librarian wants a list of the keys stored in our dictionary.

We could use the Python dictionary keys() method to get a list of keys and print them out to the console. Here's the code we would use to accomplish this task:

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

Our code returns:

title author date_published in_stock

In our code, we define a for loop that uses keys() to find the keys in our dictionary. Then, the loop iterates through each of those keys and prints them to the console. As you can see, our code returned the names of our four keys.

Iterate Using values()

The Python dictionary values() method can be used to iterate through a dictionary's values in Python. This method works in the same way as keys(), but instead returns the values in a dictionary.

Our librarian wants us to print out the values of each item in the book dictionary entry for The Great Gatsby to the console. We could do so using the following code:

Venus profile photo

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"

Venus, Software Engineer at Rockbot

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

Our code returns:

The Great Gatsby F. Scott Fitzgerald 1925 True

View the Repl.it from this tutorial:

Conclusion

To iterate through a dictionary in Python, there are four main approaches you can use: create a for loop, use items() to iterate through a dictionary's key-value pairs, use keys() to iterate through a dictionary's keys, or use values() to iterate through a dictionary's values.

This tutorial discussed how to use these four approaches to iterate through a dictionary in Python. We also explored an example of each of these methods in action. You're now ready to start iterating through Python dictionaries like a professional!

For information on top Python courses, training programs, and learning resources, check out our How to Learn Python guide.

How to Iterate Through a List in Python

Source: https://careerkarma.com/blog/iterate-through-dictionary-python/

0 Response to "How to Iterate Through a List in Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel