Python Iterate Dictionary

python iterate dictionary

In this 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

python iterate dictionary

 

You can also watch the video of this lesson!

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

python iterate dictionary

 

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

 

 

We can also use the below codes to get the keys, values and key:value pairs:

 

  • keys()
  • values()
  • items()

 

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

 

python-dictionary-for-loop-ipcisco-1

 

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

 

python-dictionary-for-loop-ipcisco-2

 

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)

 

for-loop-with-python-dictionary-ipcisco-1

 

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.

 

Back to: Python Programming Course > Python Dictionaries

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact

  • info@ipcisco.com
IPCisco is the Winner! “Best Certification Study Journey of 2019!”

Cisco-ITBlogAwards-2019-Winner-IPCisco-k