How to Iterate Through All Keys of a Dictionary in Python



Python


In this article, we show how to iterate through all keys 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 values of the keys in this particular instance. We just want the keys.

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.

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

Python has a built-in way of doing this.

If a for loop is used, looping through the dict.keys(), we can get every key 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 keys of this dictionary.

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

We then print out the keys, which are age, height, weight, gender.


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 key from the key-value pair.

This is shown in the code below.



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

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

As you see, we get age, height, weight, and gender.

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


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...