Page 1 :
have realized that Python offers many different ways to organize collections (ie, a, of values in a single “yariable”) of data items, such as strings, lists, dictionaries, tuples etc., have already worked with strings, lists and tuples in previous chapters. Now is the, work with other collection types. So, in this chapter, we shall be talking about, , about how data-items are organized in a Python, items from a dictionary, various operations that you can
Page 2 :
COMPUTER SCIENCE WITH PYTHON — XI, , DICTIONARY — KEY: VALUE PAIRS, , Among the built-in Python data types is a very versatile type called a dictionary. Dictionaries, are simply another type of collection in Python, but with a twist. Rather than having an index, associated with each data-item (just like in lists or strings), Dictionaries in Python have a “key”, and a “value of that key”. That is, Python dictionaries are a collection of some key-value pairs., Do not get confused, just read on. Just like in English dictionaries you can search for a word's, meaning, because for each word, there is a meaning associated with it. In the same manner, Python, dictionaries have some keys (just like English dictionaries have words) and associated values (just like, English dictionaries have associated meanings for every word)., Dictionaries are containers that associate keys to values, This, is, in a way, similar to lists. In lists, you must remember the Dictionaries are _ mutable,, index value of an element from the list, but with the case of unordered collections with, , dictionaries, you'll have to know the key to find the element elements in the form of a, in the dictionaries. key:value pairs that associate, keys to values., , , , , , , , All this will become clear to you while you go through, following sections., , Creating a Dictionary, , To create a dictionary, you need to include the key : value pairs in curly braces as per following, syntax :, , <dictionary-name> = { <key>:<value>, <key>:<value>... }, , Following is an example dictionary by the name teachers that stores the names of teachers as keys, and the subjects being taught by them as values of respective keys., , teachers = { "Dimple" : "Computer Science", "Kare, “Harpreet" : "Mathematics", "Sabah", , , , , "Sociology",, : "Legal Studies" }, , Notice that, the curly brackets mark the beginning and end of the dictionary,, © each entry (Key: Value) consists of a pair separated by a colon — the key and corresponding value is given by writing colon (:) between them,, , > the key-value pairs are separated by commas (,). PNoTE ag, , As you can see that there are four key : value pairs in above Pierce Be., dictionary. Following table illustrates the key-value sn es Gon ition the, relationships in above dictionary teachers. basis of keys., , , , Key-Value pair Key Value, ‘Computer Science” “Dimple” "Computer Science”, , , , , , , , , , , , , , , , ociology” "Karen" “sociology”, “Harpreet” : "Mathematics" “Harpreet" “Mathematics”, "Sabah" : "Legal Studies” "Sabah" “Legal Studies", , , , a
Page 3 :
Ee # itis an empty dictionary with no elements, nMont! anuary" : 31, "February" ; 28, "March : 31, “April” : 30, "May" : 31,, 30,, , "June" ; 30,, "October" ;, rdcount = {"Finch": 19, “Hornbill", , "July" : 31, "August" : 31, "September" :, 31, "November" ; 30, "December" : 31}, , » "Myna” : 13, "Parakeet" : 16,, +15, "Peacock" : 15} NOTE, , you can easily identify the keys and i, from above given cleteateae oe ae, , \ thing that you must know is that, just be of immutable types, such ae igo, , -a Python string, The keys ot a dictionary, ® anumber, must be of immutable types., , _ © a tuple (containing only immutable entries)., , , , If Ee ae & give a mutable type as key, Python will give you an error as: “unhashable type” >>> dict3 = {[2,3]:"abc"}, Traceback (most recent call last):, File "<ipython-input-63-477d407bcac3>, "line 1, in <module>, dict3 = {[2,3]:"abc"}, , iypeecror: unhashable type: ‘list’ Ke, , , , , , , , , , , Accessing Elements of a Dictionary, ; ae ile in li ements are, , Whil ing elements from a dictionary, you need the key. While in lists, the e, Besecd through their index ; in dictionaries, the elements are accessed through the keys, , fined in the key: value pairs, as per the syntax shown below :, , " <dictionary-name> [ <key>], : ‘Thus to access the value for key defined as “Karen” in above declared teachers dictionary, you, Thus to a, , will write :, >>> teachers["Karen”], and Python will return, , Sociology, , ‘Similarly, following statement, "Karen teaches",, , , , teachers['Karen']), >>> print (, , _ will give output as :, , Karen teaches sociology
Page 4 :
While inside brackets gives you access only, pratense mentioned key, apoesl, , , , , , ‘the name without any square br, displays the entire contents of the dictionary., Consider following example :, ies sop de (CVoweli” £73", "Vowel2" "et, "Vowel3” :"S", "Vowel4” : 70°, “Vowels” :"u"), ‘Dictionary d Displaying the contents of dictionary d ; Notice the, contains five key: 7 ‘output has shown elements in different order, | value pairs »d, , {Vowels' 'u', Voweld’ :'o', ‘Vowel’ : '1', ‘Vowel2’ : 'e’, ‘Vowel’ : 'a'}, , Printing the contents of dictionary d ; Notice the, onder of elements is different from input order, >>> print (d), , { ‘Vowels! : 'u, ‘Vowel’ ; 'o', ‘Vowel3' : '!, Vowel2': 'e’, Vowel’ ; ‘ay, , , , >>> d["Vowel1"], Accessing elements using their, - Ae re er eae ede, are the keys used to access, >>> d["Vowel4"] corresponding values., 'd, As per above examples,, , we can say that key order is not guaranteed in Python. This is because in, Python dictionaries, the elements (key : value pairs) are unordered ; one cannot access element as, per specific order. The only way to access a value is through key. Thus we can say that keys act, like indexes to access values from a dictionary., , Also, attempting to access a key that doesn’t exist causes an error. Consider the following, statement that is trying to access a non-existent key (13) from dictionary d., , ac [Nove, Traceback (most recent call last): a, File "<pyshell#7>", line 1, in <module> ‘elements (key : a) ae, dKeyEnror : 13 unordered; one cannot access, (23), , elements as per specific order., SEM, The above error means that before we can, access the value of a particular key using, expression such as d{“13“], we must first, ensure the key (13 here) exists in the dictionary., , Key Value, , Like list elements, the keys and values of a, dictionary are stored through their references., Following Fig. 9.1 illustrates the same for a, dictionary { “goose” :3, “tern” :3, “hawk”: 1), , ici, , , , Figure 9.1 References of keys and values, are stored in a dictionary
Page 5 :
‘collection means a, Means the same, makes it easy to, , ccessing and processing each element of it. Thus traversing a, and same is the tool for it , ie, the Python loops., traverse or loop over the items in a dictionary, as per follov ing,, , , , , , , , Variable <item> will be, igned indexes of Strings, f the for loop., ler following example that will illustrate this process. A dictionary namely di is defined, three keys — a number, a String, a tuple of integers., , ll={ 5: “number",\, , "a": “string",\ Recall that to break a statement/expression in multiple, (1,2) : "tuple" } lines, you can use ‘\’ at the end of physical line,, , , , assigned the keys of <Dictionary> one by one, (just like, they, or lists while traversing them), which you can use inside the, , , , , , , , , , , , , , , for key indi:, print (key, ":", di[key]), , , , loop variable key in above loop will be assigned the keys of the Dictionary di, one at a, . As dictionary elements are unordered, the order of assignment of keys may be different, om what you stored., Ising the loop variable, which has been assigned one key at a time, the corresponding value is, ited along with the key inside the loop-body using through statement :, , x it will access value from dictionary d1, _ print (key, ":", di[key]) {for given key., , t, loop-variable key will be assigned ‘a’ in first iteration and hence the key, ee Noting vil be printed ; in second iteration, key will get element (1, 2) and its, lue ‘tuple’ will be printed along with it; and so on., versing all collections is similar. You can use a for loop to get hold of, , tr, meccn sy ea or access corresponding values inside the loop-body., , idexes or keys and then, , am to create a phone dictionary for all your friends and th, r i, , , , 1 Write a prog!, , PhoneDict = { "Madhav", "pabiya’, , + 1234567, “Steven” : 7654321, “Dilpreet” : 6734521,, " » 4563217, "Murughan" : 3241567, "Sampree" : 4673215 }, in PhoneDict : ,, ES a fas mea phoneDict[name]), prin ?