Get The Most Affordable Hosting in the World!

Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.

Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!

Get Started Now!

Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the items do not have a positional index. However, traversing a dictionary is still possible with different techniques.

Example 1

Running a simple for loop over the dictionary object traverses the keys used in it.

 
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} for x in numbers: print (x)

It will produce the following output −

10
20
30
40

Example 2

Once we are able to get the key, its associated value can be easily accessed either by using square brackets operator or with get() method.

 
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} for x in numbers: print (x,":",numbers[x])

It will produce the following output −

10 : Ten
20 : Twenty
30 : Thirty
40 : Forty

The items(), keys() and values() methods of dict class return the view objects dict_items, dict_keys and dict_values respectively. These objects are iterators, and hence we can run a for loop over them.

Example 3

The dict_items object is a list of key-value tuples over which a for loop can be run as follows:

 
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} for x in numbers.items(): print (x)

It will produce the following output −

(10, 'Ten')
(20, 'Twenty')
(30, 'Thirty')
(40, 'Forty')

Here, "x" is the tuple element from the dict_items iterator. We can further unpack this tuple in two different variables.

Example 4

 
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} for x,y in numbers.items(): print (x,":", y)

It will produce the following output −

10 : Ten
20 : Twenty
30 : Thirty
40 : Forty

Example 5

Similarly, the collection of keys in dict_keys object can be iterated over.

 
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} for x in numbers.keys(): print (x, ":", numbers[x])

Respective Keys and values in dict_keys and dict_values are at same index. In the following example, we have a for loop that runs from 0 to the length of the dict, and use the looping variable as index and print key and its corresponding value.

Example 6

 
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} l = len(numbers) for x in range(l): print (list(numbers.keys())[x], ":", list(numbers.values())[x])

The above two code snippets produce identical output −

10 : Ten
20 : Twenty
30 : Thirty
40 : Forty




The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.
Ha estat útil la resposta? 1 Els usuaris han Trobat Això Útil (1 Vots)