How do you iterate over dictionaries using for loops in python?
It's not just A dictionary is a mapping of keys to values:
Any time we iterate over it, we iterate over the keys. The variable name This happens in a list comprehension:
It happens when we pass the dictionary to list (or any other collection type object):
The way Python iterates is, in a context where it needs to, it calls the
We shouldn't use these special methods ourselves, instead, use the respective
builtin function to call it,
Iterators have a
When an iterator is exhausted, it raises
Returning to dictsWe've seen dicts iterating in many contexts. What we've seen is that any time we iterate over a dict, we get the keys. Back to the original example:
If we change the variable name, we still get the keys. Let's try it:
If we want to iterate over the values, we need to use the
In the example given, it would be more efficient to iterate over the items like this:
But for academic purposes, the question's example is just fine. Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Python Dictionary Iteration: Advanced Tips & Tricks Dictionaries are one of the most important and useful data structures in Python. They can help you solve a wide variety of programming problems. This tutorial will take you on a deep dive into how to iterate through a dictionary in Python. By the end of this tutorial, you’ll know:
For more information on dictionaries, you can check out the following resources:
Ready? Let’s go! A Few Words on DictionariesDictionaries are a cornerstone of Python. The language
itself is built around dictionaries. Modules, classes, objects, Python’s official documentation defines a dictionary as follows:
There are a couple points to keep in mind:
Dictionaries are frequently used for solving all kinds of programming problems, so they are a fundamental piece of your tool kit as a Python developer. Unlike sequences, which are iterables that support element access using integer indices, dictionaries are indexed by keys. The keys in a dictionary are much like a On the other hand, values can be of any Python type, whether they are hashable or not. There are literally no restrictions for values. In Python 3.6 and beyond, the keys and values of a dictionary are iterated over in the same order in which they were created. However, this behavior may vary across different Python versions, and it depends on the dictionary’s history of insertions and deletions. In Python 2.7, dictionaries are unordered structures. The order of the dictionaries’ items is scrambled. This means that the order of the items is deterministic and repeatable. Let’s see an example: >>>
If you leave the interpreter and open a new interactive session later, you’ll get the same item order: >>>
A closer look at these two outputs shows you that the resulting order is exactly the same in both cases. That’s why you can say that the ordering is deterministic. In Python 3.5, dictionaries are still unordered, but this time, randomized data structures. This means that every time you re-run the dictionary, you’ll get a different items order. Let’s take a look: >>>
If you enter a new interactive session, then you’ll get the following: >>>
This time, you can see that the order of the items is different in both outputs. That’s why you can say they are randomized data structures. In Python 3.6 and beyond, dictionaries are ordered data structures, which means that they keep their elements in the same order in which they were introduced, as you can see here: >>>
This is a relatively new feature of Python’s dictionaries, and it’s a very useful one. But if you’re writing code that is supposed to be run in different Python versions, then you must not rely on this feature, because it can generate buggy behaviors. Another important feature of dictionaries is that they are mutable data structures, which means that you can add, delete, and update their items. It’s worth noting that this also means that they can’t be used as keys to other dictionaries, as they are not hashable objects. How to Iterate Through a Dictionary in Python: The BasicsDictionaries are an useful and widely used data structure in Python. As a Python coder, you’ll often be in situations where you’ll need to iterate through a dictionary in Python, while you perform some actions on its key-value pairs. When it comes to iterating through a dictionary in Python, the language provides you with some great tools that we’ll cover in this article. Iterating Through Keys DirectlyPython’s dictionaries are mapping objects. This means that they inherit some special methods, which Python uses internally to perform some operations. These methods are named using the naming convention of adding a double underscore at the beginning of and at the end of the method’s name. To visualize the methods and attributes of any Python object, you can use >>>
If you take a closer look at the previous output, you’ll see For mappings (like dictionaries), >>>
Python is smart enough to know that This is the simplest way to iterate through a dictionary in Python. Just put it directly into a If you use this approach along with a small trick, then you can process
the keys and values of any dictionary. The trick consists of using the indexing operator >>>
The preceding code allowed you to get access to the keys ( Iterating Through .items()When you’re working with dictionaries, it’s likely that you’ll want to work with both the keys and the values. One of the most useful ways to iterate through a dictionary in Python is by using >>>
Dictionary views like Views can be iterated over to yield their respective data, so you can iterate through a dictionary in Python by
using the view object returned by >>>
The view object returned by If you take a closer look at the individual items yielded by >>>
Once you know this, you can use >>>
Here, the variables Iterating Through .keys()If you just need to work with the keys of a dictionary, then you can use >>>
The object returned by To iterate through a dictionary in Python by using >>>
When you
call On the other hand, using the same trick you’ve seen before (indexing operator >>>
This way you’ve gotten access to the keys ( Iterating Through .values()It’s also common to only use the values to iterate through a dictionary in Python. One way to do that is to use >>>
In the previous code, As any view object, the object returned by >>>
Using It’s worth noting that they also support membership tests ( >>>
The membership test using Modifying Values and KeysIt can be pretty common to need to modify the values and keys when you’re iterating through a dictionary in Python. There are some points you’ll need to take into account to accomplish this task. The values, for example, can be modified whenever you need, but you’ll need to use the original dictionary and the key that maps the value you want to modify: >>>
In the previous code example, to modify the values of So why do you have to use the original dictionary if you have access to its key ( The real problem is that On the other hand, the keys can be added or removed from a dictionary by converting the view returned by >>>
This approach may have some performance implications, mainly related to memory consumption. For example, instead of a view object that yields elements on demand, you’ll have an entire new Finally, if you try to remove a key from >>>
This is because Real-World ExamplesSo far, you’ve seen the more basic ways of iterating through a dictionary in Python. Now it’s time to see how you can perform some actions with the items of a dictionary during iteration. Let’s look at some real-world examples. Turning Keys Into Values and Vice VersaSuppose you have a dictionary and for some reason need to turn keys into values and vice versa. In this situation, you can use a >>>
The expression Filtering ItemsSometimes you’ll be in situations where you have a dictionary and you want to create a new one to store only the data that satisfies a given condition. You can do this with an >>>
In this example, you’ve filtered out the items with a value greater than Doing Some CalculationsIt’s also common to need to do some calculations while you iterate through a dictionary in Python. Suppose you’ve stored the data for your company’s sales in a dictionary, and now you want to know the total income of the year. To solve this problem you could define a variable with an initial value of zero. Then, you can accumulate every value of your dictionary in that variable: >>>
Here, you’ve iterated through Using ComprehensionsA dictionary comprehension is a compact way to process all or part of the elements in a collection and return a dictionary as a results. In contrast to list comprehensions, they need two expressions separated with a colon followed by Suppose, for example, that you have two lists of data, and you need to create a new dictionary from them. In this case, you can use Python’s >>>
Here,
Dictionary comprehensions open up a wide spectrum of new possibilities and provide you with a great tool to iterate through a dictionary in Python. Turning Keys Into Values and Vice Versa: RevisitedIf you take another look at the problem of turning keys into values and vice versa, you’ll see that you could write a more Pythonic and efficient solution by using a dictionary comprehension:
>>>
With this dictionary comprehension, you’ve created a totally new dictionary where the keys have taken the place of the values and vice versa. This new approach gave you the ability to write more readable, succinct, efficient, and Pythonic code. The condition for this code to work is the same one you saw before: the values must be hashable objects. Otherwise, you won’t be able to use them as keys for
Filtering Items: RevisitedTo filter the items in a dictionary with a comprehension, you just need to add an >>>
Now Doing Some Calculations: RevisitedRemember the example with the company’s sales? If you use a list comprehension to iterate through the dictionary’s values, then you’ll get code that is more compact, fast, and Pythonic: >>>
The list comprehension created a If you’re working with a really large dictionary, and memory usage is a problem for you, then you can use a generator expression instead of a list comprehension. A generator expression is an expression that returns an iterator. It looks like a list comprehension, but instead of brackets you need to use parentheses to define it: >>>
If you change the square brackets for a pair of parentheses (the parentheses of Finally, there is a simpler way to solve this problem by just using >>>
Removing Specific ItemsNow, suppose you have a dictionary and need to create a new one with selected keys removed. Remember how key-view objects are like sets? Well, these similarities go beyond just being collections of hashable and unique objects. Key-view objects also support common >>>
This code works because key-view objects support Sorting a DictionaryIt’s often necessary to sort the elements of a collection. Since Python 3.6, dictionaries are ordered data
structures, so if you use Python 3.6 (and beyond), you’ll be able to sort the items of any dictionary by using >>>
This code allows you to create a new dictionary with its keys in sorted order. This is possible because For more information on how to fine-tune your sorting, check out Sorting a Python Dictionary: Values, Keys, and More. Iterating in Sorted OrderSometimes you may need
to iterate through a dictionary in Python but want to do it in sorted order. This can be achieved by using Let’s see how you can use Sorted by KeysIf you need to iterate through a dictionary in Python and want it to be sorted by keys, then you can use your dictionary as an argument to >>>
In this
example, you sorted the dictionary (alphabetically) by keys using Sorted by ValuesYou could also need to iterate
through a dictionary in Python with its items sorted by values. You can use The To sort the items of a dictionary by values, you can write a function that returns the value of each item and use this function as the >>>
In this example, you defined You may also just want to iterate through the values of a dictionary in sorted order, without worrying about the keys.
In that case, you can use >>>
ReversedIf you need to sort your dictionaries in reverse order, you can add >>>
Here, you iterated over the keys of Finally, it’s important to note that >>>
This code shows you that
Iterating Destructively With .popitem()Sometimes you need to iterate through a dictionary in Python and delete its items sequentially.
To accomplish this task, you can use If you really need to destructively iterate through a dictionary in Python, then
Here, you used a
Inside the If you run this script from your command-line, then you’ll get the following results:
Here Using Some of Python’s Built-In FunctionsPython provides some built-in functions that could be useful when you’re working with collections, like dictionaries. These functions are a sort of iteration tool that provides you with another way of iterating through a dictionary in Python. Let’s see some of them.
|