DICTIONARIES - Python Programming Made Easy (2016)

Python Programming Made Easy (2016)


A dictionary is like a list. In a list, index value is an integer, while in a dictionary index value can be any other data type and are called keys.

A dictionary is mutable and is another container type that can store any number of Python objects, including other container types. 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.

Dictionaries consist of pairs (called items) of keys and their corresponding values. Python dictionaries are also known as associative arrays or hash tables. We can refer to a dictionary as a mapping between a set of indices (which are 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.

Creating a dictionary

Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.

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.

The general syntax of a dictionary is as follows:

dict-name = {key1 : value1, key2 : value2 …. }

Example 7.1: Let’s create a dictionary that maps from numbers to number names, so the keys values are in numbers and values are in strings.


print A

We can also create a dictionary with keyword arguments and the type constructor, as long as the keys are all strings.

bob = dict(name='Bob Smith', age=42, pay=30000, job='developer')

sam = dict(name='Samuel Richard', age=45, pay=40000, job='manager')

print bob

print sam

Fig 7.2: Creating dictionary 2

We can also fill the dictionary one field at a time.

pam = {}

pam['name'] = 'Pamela Jones'

pam['age'] = 45

pam['pay'] = 40000

pam['job'] = 'Clerk'

print pam

Fig 7.3: Creating dictionary 3

Characteristics of Python Dictionaries

1. Dictionaries are Unordered

The dictionary elements (key-value pairs) are not in ordered form.


print A

Fig 7.4: Dictionary - unordered

The order of elements while the dictionary was being created is different from the order in which they are actually stored and displayed. Even if other elements are added to the python dictionary, the order is not preserved.

2. Dictionary Keys are Case Sensitive

The same key name but with different case are treated as different keys in python dictionaries.

worddict = {} # Create an empty dictionary

worddict["Raja"] = 123233

worddict["Rama"] = 123456

worddict["rama"] = 123789

print worddict

Fig 7.5: Dictionary – case sensitive

In the example above, separate elements for “Rama” and “rama” are created.

3. No duplicate key is allowed

When duplicate keys encountered during assignment, the last assignment wins. Following is a simple example:

phonebook = {"Harry":856321900, "Henry":893456782,"Sony":678903421}

print phonebook

print "Duplicating key Sony"

phonebook["Sony"] = 900235000

print phonebook

Fig 7.6: Dictionary – no duplicate key

4. Keys must be immutable

We can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Following is a simple example:

phonebook = {"Harry":856321900, "Henry":893456782,"Sony":678903421}

phonebook = { ['Name']: 'Harry', 'Age': 50}

print "phonebook['Name']:",phonebook['Name']

Fig 7.7: Dictionary – immutable keys

Accessing Values in Dictionary

To access dictionary elements, square brackets along with the key are used to obtain its value.


print A

print "A[2] =",A[2]

print "A[5] =",A[5]

Fig 7.8: Accessing values in dictionary

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


print A

print "A[10] =",A[10]

Fig 7.9: Access Error – wrong key

Updating Dictionary

An existing entry can be modified by reassigning a new value to the key.

phonebook = {"Harry":856321900, "Henry":893456782,"Sony":678903421}

print phonebook

name = raw_input("Enter name to modify: ")

if name in phonebook:

newno = raw_input("Enter new telephone number")

phonebook[name] = newno

print "Modified successfully"


print(name, "was not found")

Fig 7.10: Updating dictionary

Delete Dictionary Elements

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

phonebook = {"Harry":856321900, "Henry":893456782,"Sony":678903421}

print phonebook

name = raw_input("Enter name to delete: ")

if name in phonebook:

del phonebook[name]

print name,"deleted successfully"


print(name, "was not found")

print phonebook

Fig 7.11: Deleting dictionary elements

We can also delete entire dictionary in a single operation using the del statement.

phonebook = {"Harry":856321900, "Henry":893456782,"Sony":678903421}

print phonebook

del phonebook

print "Phonebook deleted successfully"

print phonebook

Fig 7.12: Deleting dictionary

Built-in Dictionary Functions & Methods

Python includes the following dictionary functions. For all these examples let’s assume

phonebook1 = {"Harry":856321900, "Henry":893456782,"Sony":678903421}






cmp(dict1, dict2)

This is used to check whether the given dictionaries are same or not. If both are same, it will return ‘zero’,otherwise return 1 or -1. If the first dictionary having more number of items, then it will return 1, otherwise return -1.

phonebook2 = {"Harry": 878345123, "Raja":987652341,"Sriya":908765432}

print cmp(phonebook1,phonebook2)




Gives the total length of the dictionary. This would be equal to the number of items in the dictionary.

print len(phonebook1)




Produces a printable string representation of a dictionary

print str(phonebook1)

>>{'Sony': 678903421, 'Henry': 893456782, 'Harry': 856321900}



Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type.

print type(phonebook1)

>><type 'dict'>

Table 7.1: Python Dictionary Functions

Python includes following dictionary methods







It removes all items from the particular dictionary dict.


print phonebook1

>>{ }



Returns a shallow copy of dictionary dict

phonebook2 = phonebook1.copy()

print phonebook2

>>{'Sony': 678903421, 'Harry': 856321900, 'Henry': 893456782}



Create a new dictionary with keys from seq and values set to value.

print phonebook1.fromkeys("Harry")

>>{'a': None, 'H': None, 'r': None, 'y': None}


dict.get(k, default=None)

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.

print phonebook1.get('Harry',"Harry Potter")


print phonebook1.get("Harry","Henry")


print phonebook1.get("Harry")


print phonebook1.get("Rita")




This function returns ‘True’,if dictionary has a key, otherwise it returns ‘False’.

print phonebook1.has_key("Harry")




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.

print phonebook1.items()

>>[('Sony', 678903421), ('Henry', 893456782), ('Harry', 856321900)]



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

print phonebook1.keys()

>>['Sony', 'Henry', 'Harry']


dict.setdefault(key, default=None)

Similar to get(), but will set dict[key]=default if key is not already in dict

phonebook1 = {'name': 'John', 'phone':12390007}

print phonebook1.setdefault('phone', None)




Adds dictionary dict2's key-values pairs to dict

print phonebook1.update(phonebooknew)

print phonebook1

>>{'Sony': 678903421, 'Henry': 893456782, 'Huges': 954005678, 'Harry': 856321900}



It returns a list of values from key-value pairs in a dictionary, which is not in any particular order. However, if wecall 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.

print phonebook1.values()

>>[678903421, 893456782, 954005678, 856321900]

Table 7.2: Python Dictionary Methods

Solved Programs

1. Write 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 name.


phonebook = {}

n = int (raw_input("Enter the number of entries"))

for i in range (n):

name = raw_input("Name: ")

phone = raw_input("Number: ")

phonebook[name] = phone

print phonebook

name = raw_input("Enter name to search: ")

if name in phonebook:

print("The number is", phonebook[name])


print(name, "was not found")

2. Write a program to input ‘n’ employee number and name and to display all

employee’s information in ascending order based upon their number.



n=int (raw_input("Enter total number of employees"))


while i<=n:

a=raw_input("enter number")

b=raw_input("enter name")





print "Employee Information"

print "Employee Number",'\t',"Employee Name"

for i in l:

print i,'\t',empinfo[i]

3. Write a program to form a frequency table of words in a given text.


freq={} # frequencyofwordsintext

line=raw_input("Enter text: ")


for ch in'!%.?,{''}':

line=line.replace(ch,' ')

for word in line.split():




for w inwords:


Practice Problems

1. Write the code to input any 5 years and the population of any city and print it on the screen.

2. Write a program to simulate a phonebook.

3. Write a code to create customer’s list with their number & name and delete any particular customer using his /her number.

4. Write the output for the following codes.


print A.items()

print A.keys()

print A.values()

5. 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.

6. Write a program to create a phone book and delete particular phone number using name.

7. Find errors from the following codes:


n=input(Enter total number )


while i<=n

a=raw_input("enter place")

b=raw_input("enter number")



print "place","\t","number"

for i in c:

print i,"\t",c[a[i]]