How to Iterate Through All Values of a Dictionary in Python 


               


How to Iterate Through All Values of a Dictionary in Python



Python


In this article, we show how to iterate through all values of a dictionary in Python.

So, say, we have a dictionary. This can be any dictionary.

A dictionary contains key-value pairs. Each key contains a value.

Let's say, however, that we don't want the keys but only the values in this particular instance.

Let's say we have a dictionary composed up of attributes of a person. For example, let's say we have a dictionary named Michael and we have key-value pairs of Michael's age, height, weight, gender, etc. Let's say we do not want the keys but only the values of the keys.

How can we just obtain the values of this dictionary in Python?

Python has a built-in way of doing this.

If a for loop is used, looping through with dict.values(), we can get every value in the dictionary.

This is shown in the code below.



So first we create a dictionary called Gregory.

This dictionary has 4 key-value pairs.

The first key-value pair is age:24.

The second key-value pair is height:170cm.

The third key-value pair is weight:170lbs

The fouth key-value pair is gender:male

However, we write code just to get the values of this dictionary.

So we create a for loop that goes through all of the values of this dictionary, Gregory.

We then print out the values, which are 24, 170cm, 170lbs, and male.


Alternative Way

We can also do this an alternative way.

We can go through each item in the dictionary with the items() function and simply get the value from the key-value pair.

This is shown in the code below.



So the above code is another way of obtaining all of the values from a dictionary in Python.

We simply go through each item in the dictionary and print out each value from each item.

As you see, we get 24, 170cmb, 170lbs, and male.

And this is all that is required to iterate through all values of a dictionary in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...