This technical blog is my own collection of notes , articles , implementations and interpretation of referred topics in coding, programming, data analytics , data science , data warehousing , Cloud Applications and Artificial Intelligence . Feel free to explore my blog and articles for reference and downloads . Do subscribe , like , share and comment ---- Vivek Dash
Thursday, March 11, 2021
Python program to pass Dictionary Objects into Functions ( with sample code and pictorial representation of implementation in Jupyter Notebook )
Python Program to Convert Strings into Dictionary Object ( with sample code )
Wednesday, March 10, 2021
Converting Lists into Dictionary in Python ( sample code )
Converting
Lists into Dictionary
* When we have two lists , it is possible
to convert the lists into a dictionary
* For example , we have two lists
containing the names of the countries and names of their capital cities
countries = [ "USA" ,
"India" , "Russia","China","Germany" ]
cities=["Washington","Delhi","Moscow","Beijing","Berlin"]
* If the user wants to create a dictionary
out of these two lists by taking the elements of 'countries' list as keys and
'cities' list as values , then the dictionary would look like this :
d = {
"USA":"Washington" , "India":"Delhi" ,
"Russia":"Moscow","China":"Beijing","Germany":"Berlin"}
* There are two steps involved to convert
the lists into a dictionary
Step - 01 :
Create a "ZIP" class object by
passing the two lists to the zip() function as :
z = zip(countries,cities)
The zip() function is useful to convert the
sequences into a zip class object . There may be 1 or more sequences that can
be passed to the zip() function . Therefore , we passed only 2 lists to the
zip() function in the above statement . The resultant zip object is 'z' .
Step - 02 :
The second step is to convert the zip
object into a dictionary by using the dict() function .
d = dict(z)
Here , the 0th element of the z object is
taken as the 'key' and 1st element is converted into the 'value' . On a similar
note , 2nd element is taken as the 'key' and '3rd' element is considered as the
'value' . All the values are stored in the dictionary object 'd' . If the user
wants to display 'd' object , then the user can do this by using the following
dictionary :
d = {
"USA":"Washington" , "India":"Delhi" ,
"Russia":"Moscow" , "China":"Beijing",
"Germany":"Berlin" }
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 .
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 )