man in black long sleeve shirt wearing black headphones sitting on chair
Photo by Nubelson Fernandes on Unsplash

Python is known to be the language that gives you the ability to write a few lines of code that can do a lot of things.

Just a few Python lines can be enough to pull data from an API that you can then also visualize in a fancy diagram.

Or even a single line of code can be enough for you to do plenty of things.

There are a lot of Python one-liners online that you can find.

In this article, we are going to see how to iterate through elements of a dictionary in a single line.

Before that, let’s start with iterating through elements in a list, as it can keep things rolling and seems less intimidating at first sight.

Let’s say that we have a list:

Now let’s say that we want to get only the even numbers that are on this list in a single line. Here’s how we can do that:

As you can see, it’s not that hard.

Now let’s say that we have a dictionary like the following:

Let’s say that we want to get only the elements that have odd values. 

To do that, we need to first recall that an element in a dictionary contains a key and a value and we are going to have a condition based on the value of each element in the dictionary. So we are going to get both keys and values of a dictionary.

To iterate through the dictionary, we will use the method items().

Let’s see the whole example:

We could of course get only the keys from the dictionary:

Similarly, we can get only the values:

That’s basically it. It’s that simple.

That brings us to the end of this article.

I hope you find it useful.