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 by {}:
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 display the frequency of each word in a given string.(university qstn)
S=raw_input("Enter the string…..")
S=S.split(" ") #splitting it into words
d=dict()
for w in S:
    d[w]=d.get(w,0)+1
print "word 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
Write a Python program to create a dictionary of roll numbers and names of five students. Display the names in the dictionary in alphabetical order.(university question)
d={}
for i in range(5):
    rn=input("Enter roll number..")
    name=raw_input("Enter name …")
    d[rn]=name

l=d.items()
l.sort(key=lambda v:v[1])
print "name and roll number in sorted order of name"
for i in l:
    print i[1],":",i[0]
 
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)

Quick Guide Dictionary

# key/value pairs declaration
 dict = {
 ‘key1′:’value1′,
 ‘key2′:’value2′,
 ‘key3′:’value3′
 }

#Get all keys
 dict.keys()
#Get all values
 dict.values()
#Modifying
 dict['key2'] = ‘value8′
#Accessing
 print dict['key1']
# prints ‘value2′
 print dict['key2']
# empty declaration + assignment of key-value pair
 emptyDict = {}
 emptyDict['key4']=’value4′
# looping through dictionaries (keys and values)
 for key in dict:
 print dict[key]
# sorting keys and accessing their value in order
 keys = dict.keys()
 keys.sort()
 for key in keys:
 print dict[key]
# looping their values directory (not in order)
 for value in dict.values():
 print value
# getting both the keys and values at once
 for key,value in dict.items():
 print “%s=%s” % (key,value)
# deleting an entry
 del dict['key2']
# delete all entries in a dictionary
 dict.clear()
# size of the dictionary
 len(dict)

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

  2. [The future in 2019] Trending Technologies to learn in 2019: https://www.youtube.com/watch?v=-y5Z2fmnp-o

    ReplyDelete

Post a Comment

Popular posts from this blog

Classes and Objects in Python

Python is an object-oriented programming language, which means that it provides features that support object-oriented programming. The basic components of object oriented programming are classes and objects. A Class is a blue print to create an object. It provides the definition of basic attributes and functions of objects. Object is a running instance of the class having the identity(name), properties( values) and behaviors(functions). The Object oriented program thus consist of object definitions (classes) and most of the computations and functions are mentioned as operations on the object. Each object definition corresponds to some object or concept in the real world, and the functions that operate on these object correspond to the ways real-world objects interact. We have learned objects of string, list, tuple etc…and used the properties and functionalities of these objects which are built into the Python. Now we are going to create our own(user defined) objects. Th

Identifiers,Variables and Keywords

Identifiers An identifier is a name given to entities like variables,functions,class, functions etc. It helps to differentiate one entity from another. Rules for writing identifiers 1.Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _.  Names like myClass, var_1 and print_this_to_screen, all are valid example. 2.An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name. 3.Keywords cannot be used as identifiers. Eg: global = 1 is invalid 4.We cannot use special symbols like !, @, #, $, % etc. in our identifier. a@=0 is invalid 5.An identifier can be of any length. Things to Remember Python is a case-sensitive language. This means, Variable and variable are not the same. Always give the identifiers a name that makes sense. While c = 10 is a valid name, writing count=10 would make more sense, and it would be easier to figure out what it represents when you look at your code after

NumPy Arrays

NumPy (Numerical Python)is a library for the Python programming language, adding support for large, multi-dimensional  arrays  and  matrices , along with a large collection of high-level mathematical functions to operate on these arrays. The ancestor of NumPy, Numeric, was originally created by  Jim Hugunin  with contributions from several other developers. In 2005,  Travis Oliphant  created NumPy by incorporating features of the competing Numarray into Numeric, with extensive modifications. NumPy is open-source software and has many contributors. To use the numpy package in your program, you have to import the package as follows import numpy as np Arrays A numpy array is a grid of values, all of the same type, and is indexed by a tuple of non negative integers. In NumPy dimensions are called axes.The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension. We can initialize numpy arrays