Wednesday, March 10, 2021

Using FOR loop with Dictionaries in Python - sample example

 

Using FOR loop with Dictionaries


* FOR loop is very convenient to retrieve the elements of a dictionary .One can consider a simple dictionary that contains color code in smallcase and the corresponding color combination in the following manner and its name as the following :

 

colors = { "r":"Red" , "g":"Green" , "b":"Blue" , "w":"White"}

 

Here , 'r','g','w' characters represent the keys and "Red","Green","White" indicate the values represented by the Keys  Suppose one wants to retrieve only keys from "colors" dictionary , then one can use a for loop in the following manner :

 

for k in colors:

    print(k)

 

In the above loop , one can find that the iterator variable 'k' stores each element of the colors dictionary . Here the iterator , 'k' assumes only the keys and hence the loop displays only keys . Suppose , one wants to retrieve values associated from the keys , then one can obtain them by passing the key to the colors dictionary in the form of colors(k) . The following for loop retrieves all the color values from the colors dictionary .

 

for k in colors:

    print(colors[k])

 

Since these values are associated with keys , one can retrieve them only when we mention the keys . And suppose, one wants to retrieve both the keys and their corresponding values , then one can use the items method within the for loop in the given manner :

 

for k , v in colors.items():

    print(' Key = { } Value = { } '.format(k,v))

 

In the preceding code , the colors.items() method returns an object by the name of 'dict_items' that contains key and value pairs . Each of the value pairs is stored in "k" .

  

==========================================================

Python program to show the usage of for loop to retrieve the elements of dictionaries

# One can use a for loop with dictionaries in the following manner

colors = { 'r' : "Red" ,'g' : 'Green' , 'b':'Blue' , 'w':'white'}

# display only keys

for k in colors:

    print(k)

# pass keys to the dictionary and display the values

for k in colors:

    print(colors[k])

# items method returns the key and value pair into k,v

for k,v in colors.items():

    print('Key={ } Value={ }'.format(k,v))

 

Output

b

wr

g

Blue

White

Red

Green

Key=b Value=Blue

Key=w Value=White

Key=r Value=Red

Key=g Value=Green

 

In the similar manner , another program can be written to count the number of times each letter has occurred in a string .

For example , if "Book" is a string and one is supposed to find the number of occurrences of each letter in the string , then it means that the letter "B" has occurred for 1 time , and the letter "o" has occurred for 2 times and the letter 'k' occurred for 1 time .

In this program , one can use the "get()" method very effectively . Therefore , please recollect that the get() method is used on a dictionary object item to retrieve the value by giving the key .

If the key is not found within the dictionary , then it returns some default value .

The format of the get() method is as follows :

dict.get(x,0)

This statement says that if the key 'x' is found in the dictionary 'dict' , then one must return the 'value' from the dictionary else it would return 0 as result .

One can consider the following code in order to follow or understand the manner in which the combination of key and value for a given string sequence could be mapped to a dictionary and then it could be fetched back from the code :

 

dict = { }

str = "Book"

for x in str:

    dict[x] = dict.get(x,0) + 1

 

In the given code , the last statement should be considerd once again for better understanding and clarity .

 

dict[x] = dict.get(x,0) + 1

 

If one observes the right hand expression with "get()" method then one can observe that it says if 'x' is found in the dictonary 'dict' then it should return a value otherwise it should return a 0 . As we added a '1' to the value returned by the "get()" method and therefore , if 'x' is not found , then it returns a value of 1 .

 

But if 'x' is found , then it returns the value of 'x' plus 1 . One can observe the left side expression , that is dict[x] . Here , this represents 'x' is stored as key in the dictionary . Therefore , whatever the value is returned by the right side expression , the value would be stored into that dictionary as value

for the key 'x' . This means that :

 

dict[x] = value returned by get() + 1

Let's consider the first letter of the string that is "B" . Since the dictionary is initially empty , there are no elements within the dictionary and therefore 'B' is not found within the dictionary .

 

Therefore , dict.get(x,0) + 1 returns the value 1 . In the left side , we have dict[x] which represents dict['B'] . Here , 'B' is taken as the key . And hence the statement becomes :

 

dict['B'] = 1

 

This means 'B' is stored as a key and the value 1 is stored as a value within the dictionary which means 'B' is stored as a key and the value 1 is stored as a value within the dictionary 'dict' . So , the dictionary contains a pair of elements as {'B':1} .In the next step , 'o' is the letter for which the get() method searches in the dictionary .

 

This is not found within the 'dict' and therefore 1 is returned as result . Therefore ,

 

dict['o'] = 1

 

stores the new key and value pair that is 'o' and 1 into the dictionary object 'dict' and hence the dictionary contains the following data items :

{'B':1,'o':1}

In the next repetition of for loop , we get 'o' into the value of 'x' . And since , the value is already available in the dictionary 'dict' , the value that is returned is 1 by usage of the get() method for which the value 1 is added .

 

dict['o'] = 2

 

This means that the old value of 'o' is now updated to 2 in the dictionary and 'dict' contains the elements : { 'B':1,'o':2 } . In this manner , the 'dict' stores each letter as key and its number of occurrences as value .



Ref : Core Python Programming  by Dr.Nageswara Rao (Dreamtech Publications )

No comments:

Post a Comment