Skip to main content

Dictionary In Python

Dictionaries are similar to other compound types except that they can use any immutable type as an index.
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.
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.

            Dictionaries are mutable.
            Dictionaries are unordered.
            Items in dictionaries are accessed via keys and not via their position.
A dictionary is an associative array (also known as hashes). Any key of the dictionary is associated (or mapped) to a value. The values of a dictionary can be any Python data type. So dictionaries are unordered key-value-pairs. 
Dictionaries don't support the sequence operation of the sequence data types like strings, tuples and lists. Dictionaries belong to the built-in mapping type.

Creating ,Initializing and Accessing elements
The following is the general syntax for creating a dictionary.
D = {'key1': 'value1','key2': 'value2','key3': 'value3'…'keyn': 'valuen'}
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 {}.
Example
>>>D={1:’one’,2:’two’,3:’three’}
>>>D
{1: 'one', 2: 'two', 3: 'three'}
>>>D={‘input’:’keyboard’,’output’:’monitor’,’language’:python’,’os’:’windows’}
>>>D
{'input': 'keyboard', 'os': 'windows', 'language': 'python', 'output': 'monitor'}
Note: the output is not in oder ie; the input and output are different. Thus, the order of items in a dictionary are unpredictable.

Another way to create a dictionary is to start with the empty dictionary and add
elements. The empty dictionary is denoted {}:
As an example, we will create a dictionary to translate English words into Spanish. For this dictionary, the indices are strings.

>>> eng2sp = {}
>>> eng2sp[’one’] = ’uno’
>>> eng2sp[’two’] = ’dos’
The first assignment creates a dictionary named eng2sp.We can also create an empty dictionary by dict() method.The other assignments add new elements to the dictionary. We can print the current value of the dictionary in the usual way:
>>> print eng2sp
{’one’: ’uno’, ’two’: ’dos’}
The elements of a dictionary appear in a comma-separated list. Each entry contains an index and a value separated by a colon. In a dictionary, the indices are called keys, so the elements are called key-value pairs.

The elements can be accesses with key as index using the dictionary name.
>>>D[‘os’]
'windows'
The dictionaries are mutable so we can also change the values.
>>>D[‘os’]=’linux’
>>>D
{'input': 'keyboard', 'os': 'linux', 'language': 'python', 'output': 'monitor'}
Traversing a Dictionary
No method is needed to iterate over a dictionary:
for key in d:
            print key
But it's possible to use the method iterkeys():
for key in d.iterkeys():
            print key
The method itervalues() is a convenient way for iterating directly over the values:
for val in d.itervalues():
            print val
The above loop is of course equivalent to the following one:
for key in d:
            print d[key]
Example
>>>D={'input':'keyboard','output':'monitor','language':'python','os':'windows'}
>>> for i in D:
            print i,
input os language output
>>>for i in D:
            print  D[i],
keyboard windows python monitor
>>> for i in D:
            print  i,":",D[i]," ",
input : keyboard   os : windows   language : python   output : monitor
Iterating over a Dictionary

Dynamically creating a Dictionary
In the program below, a dictionary is created dynamically with class name as the key and the values are class teacher name and strength.
n=input("Enter how many classes.....")
d=dict()
for i in range(n):
    cn=raw_input("enter class name..")
    ctn=raw_input("enter class teacher name...")
    st=input("enter strength..")
    d[cn]=ctn,st
for i in d:
    print i,":",d[i],

Appending New Values
>>>d={101:(‘manu’,30),102:(‘anu’,35)}
>>>d[103]=(‘akshay’,45)
>>>d
{101: ('manu', 30), 102: ('anu', 35), 103: ('akshay', 45)}

Merging Dictionaries
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.
>>> d1={1:10,2:20,3:30}
>>> d2={2:100,4:40,5:50}
>>> d1.update(d2)
>>> d1
{1: 10, 2: 100, 3: 30, 4: 40, 5: 50}

Removing an item from dictionary
We can remove item from the existing dictionary by using del key word.
Syntax:
del dictionaryname[key]
Example
>>> A={"mon":"monday","tue":"tuesday","wed":"wednesday","thu":"thursday"}
>>> del A["tue"]
>>> print A
{'thu': 'thursday', 'wed': 'wednesday', 'mon': 'monday'}
>>>del A  # this will delete the dictionary object.

Dictionary Functions and Methods
 len() will return the number of key-value pairs in the dictionary
>>>D={1:10,2:20,3:30}
>>>len(D)
3
items()
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.
>>>D.items()
[(1, 10), (2, 20), (3, 30)]

keys() method will return the keys as list
>>>D.keys()
[1,2,3]

values()
It returns a list of values from key-value pairs in a dictionary, which is not in any particular order.
>>> D.values()
[10, 20, 30]

clear() method will remove all elements from the dictionary.
>>>D.clear()
>>>D
{}

has_key( ) function returns ‘True’, if dictionary has a key, otherwise it returns ‘False’.
>>>D.has_key(4)
False
>>>D.has_key(2)
True
get() method returns the values corresponds to a key.If the key is not present, it will not return any value. However an optional second argument can be used to return a value in this case.
>>>D.get(3)
30
>>>D.get(4)
>>>D.get(4,-1)
-1
cmp ( )
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( it will also check the key and values if the number of elements are same), otherwise return -1.
Syntax:
cmp(d1,d2) #d1and d2 are dictionary.
returns 0 or 1 or
>>>D1={1:10,2:20,3:30}
>>>D2={1:100,2:200}
>>>cmp(D1,D2)
1

pop() method can be used to pop a value from the dictionary. It will return the value and the key-value pair is deleted from the dictionary.
>>> D={1:10,2:20,3:30}
>>> D.pop(2)
20
>>> D
{1: 10, 3: 30}

popitem() method will pop out and return the first key-value pair as a tuple .
>>> D={1:10,2:20,3:30,4:40}
>>> D.popitem()
(1, 10)
>>> D
{2: 20, 3: 30, 4: 40}

copy() method is used to create a copy of the dictionary. Note that assigning one dictionary object to another does not create a copy. It will create an alias only.
>>> D={1:10,2:20,3:30}
>>> C=D.copy()
>>> C
{1: 10, 2: 20, 3: 30}

Tuples can also be used as key
>>> D={(1,2):10,(2,3):20}
>>> D.keys()
[(1, 2), (2, 3)]

We can use in and not in to test for membership of a key in Dictionary.
>>> D={1:10,2:20,3:30}
>>> 5 in D
False
>>> 3 in D
True
Lists from Dictionaries and Dictionaries from Lists
Lists can be generated from dictionaries using the methods items(), keys() and values(). As the name implies the method keys() creates a list, which consists solely of the keys of the dictionary. values() produces a list consisting of the values. items() can be used to create a list consisting of 2-tuples of (key,value)-pairs:
>>>D={1:10,2:20,3:30}
>>>D.items()
[(1, 10), (2, 20), (3, 30)]
>>>D.keys()
[1,2,3]
>>> D.values()
[10, 20, 30]

Dictionaries can also be created from list. Two List can be combined into a list of tuples using the zip() function.The list can then be converted into a dictionary using dict() function.
>>>L1=[1,2,3]
>>>L2=[10,20,30]
>>>zip(L1,L2)
[(1, 10), (2, 20), (3, 30)]
>>> dict(zip(L1,L2))
{1: 10, 2: 20, 3: 30}

Sample Programs
Program to count the number of occurrence(frequency) of each letters in a given string( histogram)
S=raw_input("Enter the string…..")
d=dict()
for c in S:
    d[c]=d.get(c,0)+1
print "letter count"
print d

Program to read name and phn numbers of ‘n’ customers and print the list in sorted order of names

n=input("Enter number of customers..")
d={}

for i in range(n):
    nm=raw_input("Enter name..")
    phn=input("Enter phn number…")
    d[nm]=phn

l=d.items() # creating a list
l.sort() # sorting the list in the order of name.. 
             #l.sort(key=lambda v:v[1]) will sort in the order of phone number
print "name and phn number in sorted order"
for i in l:
    print i[0],":",i[1]

In the above program after printing the sorted list, read a name and delete that customer from the dictionary if present.

n=input("Enter number of customers..")
d={}
for i in range(n):
    nm=raw_input("Enter name..")
    phn=input("Enter phn number...")
    d[nm]=phn

l=d.items() # creating a list of key-vale pairs
l.sort() # sorting the list in the order of name
print "name and phn number in sorted order"
for i in l:
    print i[0],":",i[1]

k=raw_input("Enter a name to search..")
if k not in d:
    print "Not found"
else:
    print "Details..",k,":",d[k]
    del d[k] # deleting the entry
print "Dictionary after deletion"
print d

The following program uses a dictionary to convert hexadecimal number into binary.
hextobin={‘0':'0000','1':'0001','2':'0010',’3':'0011','4':'0100','5':'0101','6':'0110','7':'0111','8':'1000','9':'1001','A':'1010','B':'1011','C':'1100','D':'1101','E':'1110','F':'1111'}
n=raw_input(“Enter the hexadecimal number….”)
bn=””
for d in n:
bn=bn+hextobin[d]

print “Binary equivalent is..”,bn


Read and display a sparse matrix using dictionary ( university question)

A matrix which contains large number of zeros is called sparse matrix. A better way to represent sparse matrix is my storing only the non zero element and its index using a dictionary.
m=input("Enter the number of rows.....")
n=input("Enter the number of columns.....")
print "Enter the elements of the sparse matrix..."
A=[[0 for c in range(n)]for r in range(m)]
for r in range(m):
    for c in range(n):
        A[r][c]=input()
D={}
for r in range(m):
    for c in range(n):
        if A[r][c]!=0: #storing the non zero elements in the dictionary
            D[r,c]=A[r][c]
           
print "The Sparse Matrix is....."     
for i in A:
    print i
  
print "The Dictionary Representation is....."     

print D

Now you can try the following programs .You should also write the sample programs in Lab.
1.Create a student database using dictionary. Read rollnumber, name and mark in computer programming. Use rollnumber as key and the other data must be stored as list.List the students details in the order of roll number. Read a roll number and display the corresponding student details.Delete a particular student details after reading a roll number.
2.Read a list of numbers and print the count of each element in the list in the order.
3.Read a string and print the number of occurrence of vowels in the string.
4.Empno, name and basic pay of ‘n’ employees are stored in a dictionary. Use empno as the key. Read an empno and update the basic pay of that employee.
5.In the above program display the name and basic pay of all the employees in the order of name.
6.Read an octal number( as string) and convert into binary using a dictionary.
7. Write a python program to create a dictionary of roll numbers and names of five students. Display the content of the dictionary in the alphabetical order of names.( University Question)
8.A bookshop details contains the Title of the book and Number of copies of each title. As books are added to the shop, the number of copies to each should increase and as books are sold, the number of copies in each should decrease. Implement this scenario using dictionary data type in Python.(University Question)
9.Read a list of marks(out of 20).Count the three category of students fail(f), pass(p), firstclass(fc).
10.Read a string and find the characters which occurred most, also print their count.
11.Represent a sparse matrix using dictionary. ( refer sample program)

Comments

  1. Really appreciated the information and please keep sharing, I would like to share some information regarding online training.Maxmunus Solutions is providing the best quality of this PYTHON programming language. and the training will be online and very convenient for the learner.This course gives you the knowledge you need to achieve success.

    For Joining online training batches please feel free to call or email us.
    Email : minati@maxmunus.com
    Contact No.-+91-9066638196/91-9738075708
    website:-http://www.maxmunus.com/page/Python-Training

    ReplyDelete

Post a Comment

Popular posts from this blog

Files in Python , Exception handling

While a program is running, its data is in main memory. When the program ends, or the computer shuts down, data in memory disappears. To store data permanently, you have to put it in a file. Files are usually stored on a secondary storage device(hard disk, pen drive, DVD,CD etc). When there are a large number of files, they are often organized into directories (also called “folders”). Each file is identified by a unique name, or a combination of a file name and a directory name. By reading and writing files, programs can exchange information with each other and generate printable formats like PDF. Working with files is a lot like working with books. To use a book, you have to open it. When you’re done, you have to close it. While the book is open, you can either write in it or read from it. In either case, you know where you are in the book. Most of the time, you read the whole book in its natural order, but you can also skip around. All of this applies to files as well. To open a fil…

User Defined Functions in Python

So far we have only seen the functions which come with Python either in some file (module) or in interpreter itself (built in), but it is also possible for programmer to write their own function(s) and are called User Defined Functions. These functions can then be combined to form a module which can then be used in other programs by importing them.
In the context of programming, a function is a named sequence of statements that performs a desired operation. This operation is specified in a function definition.
To define a function keyword def is used. After the keyword comes an identifier i.e.name of the function, followed by parenthesized list of parameters and the colon which ends up the line. Next follows the block of statement(s) that are the part of function. A block is one or more lines of code, grouped together so that they are treated as one big sequence of statements while executing. In Python, statements in a block are written with indentation. Usually, a block begins when a li…