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

Understanding "with" keyword in python, on Python Hunter

J ust like anything in python, keyword "with" is introduced in python to make the things little easy. Imagine a situation where you have to manage the resources e.g opening file and closing them after the code is executed on file. To achieve this sort of task we have to write the code as follow:      Download   But if you do it often you could do this as follow to make the code reusable: Download But why do you need to do this when you know that you have to execute the only for once.  To answer this question  python-dev team finally came up with following approach: Download  Note:- Make sure you have "file.txt" and python code file in same dir. The "with"  keyword replaces the try finally block. "with" keyword executes the openFileClass() context manager and internally calls the __enter__(self) method, and whatever is being returned from __enter__(self) method is being stored in tar

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 apply import tag by pran sukh on python hunter blog

Modular Programming is good attitude of best programmer. We often need to keep our code in modular approach so that is would be easy to maintain  and update or remove dead code and also it ease the process of bug tracking. XML and XSL  processors provide freedom to import multiple imports to process the same  XML  document. In the following  XML  data we have data from collage where student's and teacher's data is given. But we want to process the same  XML  data with different XSL files. Here in this example we want to show the teacher data in red background color and student data in green background color. Data.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 <?xml version = "1.0"?> <?xml-stylesheet type = "text/xsl" href = "RootXSLT.xsl"?> <data> <DataFor name = "Student" id = "001" > <firstname>