Skip to main content

Dictionary on Python Hunter by Pran Sukh

We have learned about list in previous blogs, list can contain dictionary object vice versa. Both has the ability to change their size at run time. list and dictionary can grow and shrink according to elements at run time. But what is the actual difference b/w these two? Read below. 

  1. One is that elements from list object contains elements in linear manner but the dictionary object contains elements as key and value pair.  
  2. Elements from list object are fetched with element's location but in dictionary the elements is fetched with key.
  3. Last but not the least that list is an ordered object means when the list object is printed it shows the elements as these were inserted but dictionary sort the keys and print the values.

 Follow Python Hunter on youtube   Follow Python Hunter on twitter Follow on tumbl ( at your own risk ) check profile on linkedIn 
Examples:- 

1
2
3
dict_ = dict()
dict_ = {"Python":"Hunter","Is":"Better"}
print(dict_)


There are lot of methods to manipulate the dictionary object but some of the methods and attributes are removed from python 3.x version. Following script can be used to find the list of available methods and attributes.
1
2
for i in dir(dict_):
        print (i)


Altering Dictionary object:-
1
2
3
print(dict_["Python"])
dict_["Is"] = "Best"
print(dict_)


It is rational that a good programmer will always keep Modularity to make code readable and loosely couple. there will be some time when we want to map two dictionaries. e.g if we want to use the value of one dictionary object as key to other dictionary object, following simple example will make this concept clear.

1
2
3
4
5
d1 = {"india":"punjab","usa":"ohio"}

d2 = {"asia":"india","west":"usa"}

print(d1[d2["asia"]])



We can not use list object as key in dictionary, dictionary objects are fetched with key and key needs to be fixed, and as we know from previous post that list can be altered at run time. so if we will use list as key in dictionary and list keeps getting updated every time the program executes then it will be tough for us to get the dictionary object, so that's why python does not allow us to use the list object as dictionary key. but list object can be used as dictionary value. 

1
2
d3 = {[1,2,3]:"value","key2":"value2"}
print(d3)

the above code snippet will give you following error.
TypeError: unhashable type: 'list'

But tuples object can be used as dictionary key as the tuple object can not be altered at run time.
1
2
d3 = {(1,2,3):"value","key":"value"}
print(d3)


Only unique is allowed in dictionary, if there is any duplicate key in dictionary then the old value of that key will be replaced by new value. See the example.
1
2
d3 = {"key":"value1","key":"value2","key":"value3"}
print(d3)

As we can see the key is repeated thrice but as the rule says only one unique key in allowed in dictionary so the last value "value3" will be updated in key and all other previous values will be discarded.


Just like list and tuple the dictionary object can also have inner dictionary object and the approach to get the inner dictionary is as same as the list and tuple object.


1
2
3
4
5
d4 = {"Python":"Hunter","Is":"Great","InnerDicStart":{"innerDicKey":"InnerDictValue"}}

print(d4["InnerDicStart"])

print(d4["InnerDicStart"]["innerDicKey"])


Operation on Dictionary object:-

1
2
3
4
5
6
7
d4 = {"Python":"Hunter","Is":"Great","InnerDicStart":{"innerDicKey":"InnerDictValue"}}

len(d4) #returns the number of keys

print("InnerDicStart" in d4) # returns true if key 'Is' is present.

print("nonExsitingKey" not in d4) # true if key is not present in dict


but key 'innerDicKey' is not visible with 'in' operator, first we have to get the inner dictionary then 'in' operator will work fine.


1
print("innerDicKey" in d4["InnerDicStart"])

Note:- When we try to access non-existing key then python gives us following
keyError 'Your_key'

Like list, tuple and string dictionary objects can also be merged and updated. The only difference in merging dictionary object is that the new keys will be inserted an existing keys will update with new value. e.g.

1
2
3
4
5
6
7
d5 = {"Python":"Hunter","Is":"good"}

d6 = {"and":"cool","Is":"great"}

d5.update(d6)

print(d5)
This code shows that dictionary object d5 will be updated with d6 keys and its value. but key "Is" is already presented in d5 so the the key value in d5 will be updated with d6's value and  final out put will be as below.
{'Python': 'Hunter', 'Is': 'great', 'and': 'cool'}
Value of key "Is" is update with "great" from d6



It is possible to separately iterate over keys and value. But both methods in are deprecated in Python 3.x but working fine in Python 2.x. If you have Python 2.x installed on your system then the below code will work fine otherwise on Python 3.x it will show errors.

1
2
3
4
5
6
7
8
#in ptyhon 3.x iterkeys() does not exist.
for key in d5.iterkeys():
 print (key)

#iter over values
#in ptyhon 3.x itervalues() does not exist.
for key in d5.itervalues():
 print (key)




Converting Dictionary object to list object.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
d7 = {"key1":"value1","key2":"value2","key3":"value3"}

list_ = d7.items()

list_of_keys = d7.keys()

list_of_values = d7.values()

print(list_)

print(list_of_keys)

print(list_of_values)



Converting List object to Dictionary object.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
list_1 = ["key1","key2","key3","key4"]
list_2 = ["value1","value2","value3","value4"]

newDict = dict ()
newDict = zip(list_1,list_2)
print(newDict)

# transfor into real dict
actualDict = dict (newDict)
print(actualDict)
But wait !!! what has happened to value4 in list_2 
The over flowing keys or values will be discarded. This is the smartness of python, otherwise it is not good to show error every time.

Comments

Popular posts from this blog

XML, XSLT info by pran sukh on Python Hunter blog.

What is XML? Many computer systems contain data in incompatible formats. Exchanging data between incompatible systems (or upgraded systems) is a time-consuming task for web developers. Large amounts of data must be converted, and incompatible data is often lost. XML stores data in plain text format. This provides a software- and hardware-independent way of storing, transporting, and sharing data. XML also makes it easier to expand or upgrade to new operating systems, new applications, or new browsers, without losing data. With XML, data can be available to all kinds of "reading machines" like people, computers, voice machines, news feeds, etc. XML:- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 <?xml version="1.0" encoding="UTF-8"?> <bookstore> <book category= "cooking" > <title lang= "en" > Every

Understanding the usage of underscore( _ ) of Python for beginner. On Python Hunter

Introduction: Just like you, a newbie in python scripting language, me too was confused about lot of new things in python that are not valid or available in other languages like Java, .Net etc. Just like other things i had seen the use of '_' underscore in python, at beginning level that flabbergasted me for a while.      With some research and practice i have summarised the following usage of '_' underscore in python. Hope you will find it helpful at beginning level. First Usage : Hold the previous output value. When used in interpreter. 1 2 3 4 5 6 7 _ = input () # For example you typed '5' print (_) # This will print '5' print ( int ( _ ) * int ( _ ) ) # This will print '25' print ( int ( _ ) + 10 ) The above will print '15', because last input was "5" and in above   line of code is producing '25' as output but not being handl

XSLT applyTemeplate tag by pran sukh on Python Hunter.

XSLT is used for presenting XML data in well structured way and in eye appealing sense. In XSLT we can define different templates and maintain criteria for XSLT processor to parse the XML data in and apply different template for different XML tags. Lets examine following example XML DATA. 1 2 3 4 5 6 7 8 9 10 <student id= "1" eCode= "e1" > <firstName> Python 1 </firstName> <lastName> Hunert 1 </lastName> <dob> <day> 01 </day> <month> Jan </month> <year> 1991 </year> </dob> <course> Programmer </course> </student> In above XML data we want to present student id with dark background and eCode with red background colors, First Name in blue color, last name in green color and date of birth in different modes, so it will look like this. Source File:- XML_DATA.xml 1 2 3 4 5 6 7 8 9 10