In this Python lesson, we will focus on Python Iterate Dictionary examples. We will learn how to use iteration with Python Dictionaries. Here, we will focus on for loops and how to us efor loops with dictionaries.
While using loops like below, we get key values like below:
character ={
"race": "wizard",
"name": "Gandalf",
"color": "grey",
}
for x in character:
print(x)
The output of this python iterate dictionary example will be like below:
race
name
color
You can practice below!
You can also check Python Dictionary Access Method
You can also watch the video of this lesson!
You can learn all Python Dictionary Methods
So, if you would like to access values of key:value pair, what will you do? In this time we will use the index value between square brackets with the name of the dictionary.
character ={
"race": "wizard",
"name": "Gandalf",
"color": "grey",
}
for x in character:
print(character[x])
The output of this python iterate dictionary code will be:
wizard
Gandalf
grey
We can do another examples with network devices like below:
device ={
"vendor": "Cisco",
"model": "9000 series",
"RU": 44
}
for x in device:
print(device[x])
Cisco
9000 series
44
You can also check Python Dictionary Add Method
We can also use the below codes to get the keys, values and key:value pairs:
Now, let’s do some examples with for loops and these keywords. Firstly, let’s get keys as output.
device ={
"vendor": "Cisco",
"model": "9000 series",
"RU": 44
}
for x in device.keys():
print(x)
vendor
model
RU
Now, let’s ee only values of the dictionary.
device ={
"vendor": "Cisco",
"model": "9000 series",
"RU": 44
}
for x in device.values():
print(x)
Cisco
9000 series
44
Laslty, let’s get both keys and values of the dictionary with item keyword.
device ={
"vendor": "Cisco",
"model": "9000 series",
"RU": 44
}
for x in device.items():
print(x)
('vendor', 'Cisco')
('model', '9000 series')
('RU', 44)
In this lesson, we have learned how to use for loop with dictionaries. You can increase your examples as python iterate dictionary. With more examples, you will learn this lesson better. We use for loops on Python dictionaries like python lists and python tuples.
Leave a Reply