7.0 Dictionaries

Syllabus : The Dictionary Data Type, Pretty Printing, Using Data Structures to Model Real-World Things.

7.1 What is dictionary?

A dictionary is a collection of items that are unordered, changeable and indexed. Dictionary items are made up of Key – value pair and each key is separated from its value by a colon(: ) and whole thing is enclosed in curly braces.

Example :

Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. A dictionary is an extremely useful data storage construct for storing and retrieving all key value pairs, where each element is accessed (or indexed) by a unique key. However, dictionary keys are not in sequences and hence maintain no left-to right order.

Dictionary is a mapping between a set of indices ( called keys) and a set of values. Each key maps a value. The association of a key and a value is called a key-value pair.

 my_dict = {'key1': 'value1','key2': 'value2','key3': 'value3'…'keyn': 'valuen'}

7.2 Creating Dictionaries :

7.2.1 Creating Empty Dictionary :

7.2.2 Creating Dictionary with Multiple Elements

Example 1:

Example 2 :

7.3 Accessing Values in Dictionary

To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. Following is a simple example :

If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows –

7.4 Updating Dictionary

Dictionary can be updated by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example :

7.5 Delete Dictionary Elements

You can either remove individual dictionary elements or clear the entire contents of a dictionary.

You can also delete entire dictionary in a single operation. To explicitly remove an entire dictionary, just use the del statement. Following is a simple example −

7.6 Properties of Dictionary Keys

Dictionary Values have no restrictions and that they can be of any arbitrary object. Keys are immutable type with following properties :

  1. More than one entry per key is not allowed . When duplicate key is allowed the last assignment wins :

2. Since Keys are immutable , one can use strings , numbers or tuples as dictionary keys.

7.7 Python Dictionary items() method

It returns the content of dictionary as a list of key and value. The key and value pair
will be in the form of a tuple, which is not in any particular order.

Syntax : dictionary.items()

Example :

7.8 Python Dictionary keys() method

It returns a list of the key values in a dictionary, , which is not in any particular order.

Syntax : dictionary.keys()

Example :

7.9 Python Dictionary Values Method

It returns a list of values from key-value pairs in a dictionary, which is not in any particular order. However, if we call both the items () and values() method without changing the dictionary’s contents between these two (items() and values()), Python guarantees that the order of the two results will be the same.

Example 1:Traversing Dictionary using keys

Example 2 : Traversing Dictionary using values

Example 3 : Traversing Dictionary using values

Example4 : Checking Whether a key or value exists in a dictionary

7.10 Comparing Dictionaries

7.11 Merging dictionaries: An update ( )

Two dictionaries can be merged in to one by using update ( ) method. It merges the keys and values of one dictionary into another and overwrites values of the same key.

Syntax:  Dic_name1.update (dic_name2) 
Using this dic_name2 is added with Dic_name1. 

7.12 len( )

This method returns number of key-value pairs in the given dictionary.

7.13 get(k, x )

There are two arguments (k, x) passed in ‘get( )’ method. The first argument is key value, while the second argument is corresponding value. If a dictionary has a given key (k), which is equal to given value (x), it returns the corresponding value (x) of given key (k). However, if the dictionary has no key-value pair for given key (k), this method returns the default values same as given key value. The second argument is optional. If omitted and the dictionary has no key equal to the given key value, then it returns None.

Syntax:  D.get (k, x) #D dictionary, k key and x value

7.14 setdefault() method

The setdefault() method returns the value of the item with the specified key.If the key does not exist, insert the key, with the specified value, as illustrated below:

Syntax : dictionary.setdefault(keyname, value)

Example : Get the value of the “color” item, if the “color” item does not exist, insert “color” with the value “silksilver”:

7.15 Converting a dictionary to a list of tuples

Dictionary have a method called items() that returns a list of tuples where each tuple is a key value pair.

7.16 Pretty Printing

“Prettyprint” is defined as a process where the source code or any other item is displayed in an attractively presentable way. In the below article, we will learn about the concepts of pretty print dict Python with three different methods to implement it. We can pretty print dict Python by importing the ‘pprint’ module in Python which gives the capability to “pretty-print” random data structures in a much more presentable form that can also be used as input to the interpreter.

7.17 Questions for Practice:

  1. a python program to input ‘n’ names and phone numbers to store it in a
    dictionary and to input any name and to print the phone number of that particular
  2. What is Dictionary ? List merits of Dictionaries over List.
  3. Write a python program to accept USN and marks obtained, find maximum ,minimum and students USN who have scored in the range 100 -85, 85-75, 75-60 and 60 marks separately
  4. Discuss the following Dictionary methods in Python with examples.
    • a. get()
    • b. items()
    • c. keys()
    • d. values()
  5. What is dictionary ? Illustrate with an example python program the usage of nested dictionary.
  6. What is the difference between copy.copy() and copy.deepcopy() functions applicable to a list or dictionary in Python? Give suitable examples for each.
  7. Write a program to input ‘n’ employee number and name and to display all
    employee’s information in ascending order based upon their number.
  8. Write a program to create a phone book and delete particular phone number using name.
  9. Write the code to input any 5 years and the population of any city and print it on the screen.
  10. Write a code to input ‘n’ number of subject and head of the department and also display all information on the output screen.
  11. Write a code to create customer’s list with their number & name and delete any particular customer using his /her number.
  12. Write a Python program to input ‘n’ names and phone numbers to store it in a dictionary and print the phone number of a particular name.
  13. Write the output for the following Python codes.