How to Loop Through a Dictionary

We can use For loop to access item in dictionary. There are several ways to be done, but the most common methods involve using the `.keys()`, `.values()`, and `.items()` methods. Here is how to loop through a dictionary.

The example below show that :

x is defined as key of myDict. So x will be assigned all key’s name from myDict.

myDict = {'a': 100, 'b': 200, 'c': 300}
for x in myDict:
    print(myDict[x])

Output: accessing all values in dictionary by key that assigned to x

100
200
300
How to Loop Through a Dictionary By using method items()

Another technique to use loop through dictionary is items method. The items() method can use to access item with both key and value through loop. Let see the example below:

Example:

x is defined to assigned as key while y is defined to assigned as value.

myDict = {'a': 100, 'b': 200, 'c': 300}
for x,y in myDict.items():
    print(x,"=",y)  

Output:

a = 100
b = 200
c = 300

freecode4learn.com

Leave a Reply