Dictionary in Python PYTHON by Ravinder Nath Rajotiya - March 28, 2022March 29, 20220 Share on Facebook Share Send email Mail Print Print Table of Contents Toggle DICTIONRY IN PYTHONDeclaration :Dictionary in python is similar to List in python.However there are differences between them, these are:Operations on dictionaryCreating Disctionaryi. Specifying a list of comma-separated <key>:<value> pairs enclosed in curly bracesii. Passing a list of tuples to the built-in dict()functioniii. Another way, Passing a list of tuples to the built-in dict()functioniv. Passing keyword arguments to the dict()function (if the key values are simple strings)v. Creating an empty dictionary and then assigning the key-value pairs individuallyAccessing Disctionarywhole dictionary as key:value pairsBy using keys asAdding items in dictionaryDeleting Items from a dictionary:Delete a whole dictionayNameError: name ‘tel’ is not definedDeleting items using a ‘key’Sorting the dictionary itemsBoolean operations on dictionaryLooping in dictionarycreating a dictionary using loopii. use variable for key and its value for a for loopZip function on dictionaryDictionary ComprehensionOutput DICTIONRY IN PYTHON Dictionary is a composite data type. It is used to represent records. The items in dictionary are represented by the key: value pairs. Declaration : A dictionary is declared by enclosing a comma-separated list of key-value pairs in curly braces. The value of an item is always accessed by using its key, therefore the key must be a unique name. Example dict={<key1> : <value>, <key2> : <value>, <key3> : <value>…….<keyn> : <value>} Th following define a dictionay that maps the capital to its country. capital_country = {‘Delhi’ : ‘India’, ‘Karachi’, ‘Pakistan’, ‘Kathmandu’ : ‘Nepal’ } Dictionary in python is similar to List in python. Let us see the similarty and differences between list and dictionary LIST DICTIONARY Is mutable Is mutable Can grow and shrink Can grow and shrink Can be nested Can be nested However there are differences between them, these are: LIST DICTIONARY Is declared using [] braces, Ex x=[2,4,6,8] Is declared using {} braces. Ex x={ ‘a’:1, ’b’:2, ’c’:3 } List elements are accessed by their position in the list, via indexing Dictionary elements are accessed via keys. Operations on dictionary Creating Disctionary i. Specifying a list of comma-separated <key>:<value> pairs enclosed in curly braces >>> dic = { ‘first’: 1, ‘second’:2, ‘third’ : 3 } ii. Passing a list of tuples to the built-in dict()function >>> d=dict({(‘f’,1),(‘g’,2),(‘h’,3)}) >>> d {‘f’: 1, ‘g’: 2, ‘h’: 3} iii. Another way, Passing a list of tuples to the built-in dict()function >>>d=dict([ (‘f’,1), (‘g’,2), (‘h’,3) ]) iv. Passing keyword arguments to the dict()function (if the key values are simple strings) >>> d=dict(f=1,g=2,h=3) v. Creating an empty dictionary and then assigning the key-value pairs individually >>> d = {} >>> d[‘f’] = 1 >>> d[‘g’] = 2 >>> d[‘h’] = 3 >>> d {‘f’: 1, ‘g’: 2, ‘h’: 3} *Note – The following does not create a dictionary, but creates a set >>> d={(‘f’,1),(‘g’,2),(‘h’,3)} >>> d {(‘f’, 1), (‘g’, 2), (‘h’, 3)} # it does not contain key:value pair, it is not a dictionary, but is a set Accessing Disctionary A dictionary values can be accessed as a whole by its name or by using the keys, for example dic = { ‘first’: 1, ‘second’:2, ‘third’ : 3 } whole dictionary as key:value pairs >>> dic = { ‘first’: 1, ‘second’:2, ‘third’ : 3 } >>>dic {‘first’: 1, ‘second’: 2, ‘third’: 3} By using keys as >>> Std_Data = {‘atul’: ‘Y22001’, ‘Bhawna’: ‘Y22002’, ‘Chetna’ : ‘Y22003’ } >>> Std_Data[‘Bhawna’] ‘Y22002’ Adding items in dictionary We can add items to an already exisitng dictionry. Assume that a dictionary ‘dic’ already exists. Then we can add items as: dic[<key>]=<value> >>> dic ={‘x’:1} # create a dictionary >>> dic[‘atul’] = ‘name’ # Add items at the end of dictionary >>> dic {‘x’: 1, ‘atul’: ‘name’} # Note that we can only add items to an already existing blank dictionary or to a dictionary with items. If you try adding to a non-existing dictionary using dic[<key>]=<value> , an error will occur. >>>fruit_tastes[‘grapes’]=’soar’ # will give error , non-existing dictionary ‘fruit_tastes’ fruit_tastes[‘grapes’]=’soar’ ^ SyntaxError: invalid character in identifier #Error – You cannot define a dictionary with item value starting with zero (0) or a string without quote. An error as follow will occur. Example: >>> tel={‘smita’: 0123, ‘baibhav’: 2345, ‘ravinder’: 4567} ^ SyntaxError : leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers Deleting Items from a dictionary: We can delete a whole dictionay just using del <dictionary_name> or any item of a dictionary by using its key as: Delete a whole dictionay >>> tel={‘smita’: 0123, ‘baibhav’: 2345, ‘ravinder’: 4567} >>> del tel # deletes the whole dictionary, then if you access again by its name, an error occurs >>> tel #will give error because dictionary tel now does not exist NameError: name ‘tel’ is not defined Deleting items using a ‘key’ >>> tel={‘smita’: 123, ‘baibhav’: 2345, ‘ravinder’: 4567} >>> tel {‘smita’: 123, ‘baibhav’: 2345, ‘ravinder’: 4567} >>> del tel[‘smita’] >>> tel {‘baibhav’: 2345, ‘ravinder’: 4567} Now again add an item to this dictionary >>> tel[‘smita’]=1234 >>> tel {‘baibhav’: 2345, ‘ravinder’: 4567, ‘smita’: 1234} >>> del tel[‘ravinder’] >>> tel {‘baibhav’: 2345, ‘smita’: 1234} Sorting the dictionary items Dictionary items can be sorted based on its key. For this, we use the sorted() method for a dictionary >>> tel = {‘baibhav’: 2345, ‘smita’: 1234, ‘ravi’: 1020} >>> tel {‘baibhav’: 2345, ‘smita’: 1234, ‘ravi’: 1020} >>> sorted(tel) [‘baibhav’, ‘ravi’, ‘smita’] Boolean operations on dictionary Boolean operations on a dictionary will return ‘TRUE’ or ‘FALSE’ Example-1 >>> tel = {‘baibhav’: 2345, ‘smita’: 1234, ‘ravi’: 1020} >>> tel {‘baibhav’: 2345, ‘smita’: 1234, ‘ravi’: 1020} >>> ‘smita’ in tel True >>> ‘ravinder’ in tel False >>> ‘ravinder’ not in tel True Example-2: >>> dic = {‘first’: 1, ‘second’:2, ‘third’ : 3 } >>> dic {‘first’: 1, ‘second’: 2, ‘third’: 3} >>> ‘second’ in dic True >>> ‘second’ not in dic False Looping in dictionary creating a dictionary using loop >>> {x:x**2 for x in (2,3,4,5)} {2: 4, 3: 9, 4: 16, 5: 25} >>> {x:x**3 for x in (2,3,4,5)} {2: 8, 3: 27, 4: 64, 5: 125} >>> tel = {‘baibhav’: 2345, ‘smita’: 1234, ‘ravi’: 1020} >>> tel {‘baibhav’: 2345, ‘smita’: 1234, ‘ravi’: 1020} ii. use variable for key and its value for a for loop >>> for a,b in tel.items(): … print(a,b) … baibhav 2345 smita 1234 ravi 1020 >>> x={‘smita’: ‘is a girl’, ‘baibhav’: ‘is a boy’, ‘ravinder’: ‘ isa man’} >>> x {‘smita’: ‘is a girl’, ‘baibhav’: ‘is a boy’, ‘ravinder’: ‘ isa man’} >>> for a, b in x.items(): … print(a,b) … smita is a girl baibhav is a boy ravinder isa man Zip function on dictionary >>> que=[‘name’, ‘favorite_color’, ‘Read’] >>> que [‘name’, ‘favorite_color’, ‘Read’] >>> ans=[‘smita’, ‘pink’, ‘novels’] >>> ans [‘smita’, ‘pink’, ‘novels’] >>> for a,b in zip(que, ans): … print(‘what is your {0}? It is {1}.’.format(a, b)) … what is your name? It is smita. what is your favorite_color? It is pink. what is your Read? It is novels. The zip(fields, values) method returns an iterator that generates two-items tuples. If you call dict() on that iterator, you can create the dictionary you need. The items of the first list become the dictionary’s keys, and the elements second list represent the values in the dictionary. l1 = [1, 2, 3, 4] l2 = [5, 6, 7, 8] print('Result: {}'.format({a : b for a,b in zip(l1, l2)})) This prints a dictionary: {1: 5, 2: 6, 3: 7, 4: 8} A series of tuples a,b are generated successively by iterating through the zipped list and from each tuple a,b a key-value pair a:b is generated, abeing the key and bbeing the value. Dictionary Comprehension Dictionary comprehension is an elegant and concise way to create dictionaries. For example, we can use the above example to create a dictionary from two lists. The minimal syntax for dictionary comprehension is the following. >>>Dictionary = {key:value for vars in iterable} #See the following code example of dictionary comprehension. >>>Stocks = [‘JIMS’, ‘amity’, ‘lingayas’] >>> = [2159, 1112, 2876] >>>new_dict = {stocks:prices for stocks, prices in zip(stocks, prices)} Output >>>new_dict {‘JIMS’: 2175, ‘amity’:1127, ‘lingayas’:2750} Share on Facebook Share Send email Mail Print Print