[go: up one dir, main page]

0% found this document useful (0 votes)
24 views13 pages

Notes on dictionary2

Computer science

Uploaded by

mahekagrawal01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views13 pages

Notes on dictionary2

Computer science

Uploaded by

mahekagrawal01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Notes on dictionary ( by : K.

Shridhar)

Dictionaries is a data structure in which we store values as pair of key and value, each key is separated
from its value by a colon and consecutive items are separated by commas. The entire item in a
dictionary are eclosed in curly brackets ( { } )
Syntax for defining Dictionary
Dictionaryname = { key1:value1,key_2:value2,key_3:value3}
Dictionaries in python have a key and a value of the key “ not the index in just like lists, tuples”. Python
dictionary are a collection of some key value pairs. Just like English dictionary we can search for a
word’s meaning. Python dictionaries have some keys (just like English dictionary have words) and
associated values. In other words dictionaries are mutable, unordered collection with elements in the
form of a key value pairs that associated keys to values.
Creating dictionary
Dictionaryname = { key1:value1,key2:value2,key3:value3}
As per syntax :
Teachers={“English”:”Mrs.Singh”,”hindi”:”Mrs.Kiran”,”physics”:”Mr.Suresh”,”computer”:”Mr.Shridhar”,
”chemistry”:”Mrs.Mini”}
Here Teachers is the name of the dictionary
Keys are : English, hindi, physics, computer, chemistry
Value: Mrs. Singh,Mrs. Kiran, Mr. Suresh, Mr. Shridhar, Mrs. Mini
Note:
1. keys must be unique and be of any immutable data type.
2. Dictionaries are not sequence, rather they are mappings. Mappings are collections of objects
that store objects by key instead of by relative position .
3. Dictionary keys are case sensitive. Two keys with the same name but in different case are not
the same in python .
4. A dictionary can be also created by specifying key value pairs separated by a colon in curly
brackets as shown below. Note that one key value pair is seprated from the other using a
comma.
Dict={‘rollno’:’1’,’name’:’akashat’,’course’:’BTech’}
print(Dict) output: {‘rollno’:’1’,’name’:’akashat’,’course’:’BTech’}
5. Internally dictionaries are indexed on the basis of keys.
6. Dictionaries are also called associative arrays or mapping or hashes.
7. If we try to give a mutable type as keys python will give an error as – “ unhashable type”
For ex.
Dict1={[2,3]:”xyz”}
print(Dict1) # this will give error like : TypeError: unhashable type : “List”
8. To create a dictionary with one or more key value pairs we can also use the dict() function. The
dict() function creates a dictionary directly from a sequence of key value pairs. For ex.
print(dict([(‘rollno’,’1’),(‘name’,’anchal’),(‘course’,’MTech’)]))
program to create 10 key value pairs where key is a number in range 1-10 and the value is twice the
number
dicti={x:2*x for x in range(1,11)}
print(dicti) output: {1:2,2:4,3:6,4:8,5:10…………10:20)
the above example is called dictionary comprehensions. A dictionary comprehensions is a construct
which creates a dictionary based on existing dictionary syntax is :
d={ expression for variable in sequence [if condition]}
accessing elements/values of a dictionary
while accessing elements from a dictionary we need the key
for ex.
print(“computer is teach by “,teachers[‘computer’]) output: computer is teach by Mr.Basil

to access values in a dictionary, square brackets are used along with the key to obtain its value.
Program to create a phone dictionary for all your friends and print it.
Phdict={‘shri’:9826939830,’basil’:123456789,’akarsh’:987654321,’sahitya’:56565656,’raman’:55445544}
for name in phdict:
print(name,”:”,phdict[name])
output: shri:9826839830
basil:123456789
----
----
Adding and modifying an item in a dictionary
Syntax to add an item in a dictionary :
Dictionary variable[key]=value
For ex.
Program to add a new item in a dictionary
Dict1={‘rollno’:’1’,’name’:’akashat’,’course’:’BTech’}
print(“roll no.=”,Dict1[‘rollno’])
print(“name=”,Dict1[‘name’])
print(“course=”,Dict1[‘course’])
Dict1[‘marks’]=95 # new entry
print(“marks=”,Dict1[‘makrs’])
to modify an entry , just overwrite the existing value.
Dict1={‘rollno’:’1’,’name’:’akashat’,’course’:’BTech’}
print(“roll no.=”,Dict1[‘rollno’])
print(“name=”,Dict1[‘name’])
print(“course=”,Dict1[‘course’])
Dict1[‘marks’]=95 # new entry
print(“marks=”,Dict1[‘makrs’])
Dict1[‘course’]=’BCA’
print (“Dict1[course]=”,Dict1[‘course’]) # entry updated with BCA
deleting item from dictionary
we can delete one or more items using the del keyword. To delete or remove all the items in just one
statement, use the clear() function . finally to remove an entire dictionary from the memory, we can
again use the del statement as del Dict_name. Syntax
del dictionary_variable[key]
for ex.
Dict1={‘rollno’:’1’,’name’:’akashat’,’course’:’BTech’}
print(“roll no.=”,Dict1[‘rollno’])
print(“name=”,Dict1[‘name’])
print(“course=”,Dict1[‘course’])
del Dict1[‘course’] # deletes a key-value pair
Dict1.clear() # deletes all entries
del Dict1 # deletes the variable Dict1 from the memory

we can also use the pop() function to delete a particular key from the dictionary syntax
dict.pop(key[,default]) as the name suggests the pop() function removes an iem from the dictionary
and returns its value, if the specified key is not present in the dictionary then the default value is
returned, if we do not specify the default value and the key is also not present in the dictionary then a
key error is generated. Another method dict.popitem() randomly pops and returns an item from the
dictionary.
Program for randomly pop() or remove an element from a dictionary
Dict={‘rollno’:1,’name’:’shri’,’course’:’BTech’}
print(“name is:”,Dict.pop(‘name’))
print(“dictionary after poping name is “,Dict)
print(“randomly popping any item”,Dict.popitem())
print(“dictionary after random popping is :”,Dict)
print(“aggregate is “,Dict.pop(‘agge’)) # generates error
print(“Dictionary after popping aggregate is :”,Dict)
Key points to be remember
 keys must have unique values, not even a single key can be duplicated in a dictionary
 in a dictionary keys should be strictly of a type that is immutable. This means that a key can be
of strings, numbers or Tuple type but it can not be a list which is mutable.
 Tuples can be used as keys only if they contain immutable objects like strings, numbers or other
Tuples. If a Tuple used as key contains any mutable objects either directly or indirectly then
error is generated. For ex. Dict={(1,2),([4,5,6])]
Print(Dict)
 The in keyword can be used to check whether a single key is present in the dictionary for ex.
Dict={rollno’:1,’name’:’shri’,’corse’:’Btech’}
If ‘course’ in Dict :
print (Dict[‘course’]) # output : Btech

sorting items in a dictionary


The key() method of dictionary returns list of all the keys used in the dictionary in an arbitrary order.
The sorted () function is used to sort the keys. For ex.
Dict={‘rollno’:1,’name’:’shri’,’course’:’Btech’}
print(sorted(Dict.keys()))# output: [course,name,rollno]
Looping over a dictionary
We can loop over a dictionary to access only values, only keys and both using the for loop for ex.
Program to access items in a dictionary using for loop.
Dict ={‘rollno’:1,’name’:’shri’,’course’:’Btech’}
print(“kyes:” end=’ ‘)
for key in Dict:
print(key,end=’ ‘) # accessing only keys
print(“\n values:”,end=’ ‘)
for val in Dict.values():
print(val,end=’ ‘) # accessing values
print(“\n Dictionary :”,end=’ ‘ )
for key,val in Dict.items():
print(key,val,”\t”, end=’ ‘) # accessing keys & values
output:-
keys: rollno,name,course
values: 1, shri, Btech
Nested Dictionaries
We can also define a dictionary inside another dictionary which is called nested dictionary for ex.
Program to show nested dictionary
Students={‘sahitya’:{‘cs’:90,’maths’:94,’phy’:92}’akshat’:{‘cs’:91,’maths’:94,’phy’:,96},
‘anchal’:{‘cs’:98,’maths’:93,’phy’:95}}
for key,val in Student.items():
print(key,val)
output:
sahitya {cs 90 maths 94 phy 92}
akshat { }
anchal{

programs on Dictionary

PROGRAM NO 1
#WAP to create a dictionary containin names of competitions winner student
#as key and number of their wins as values
n=int(input("how many students ?"))
wins={}
for i in range(n):
key=input("name of the student:")
value=int(input("number of competitions won:"))
wins[key]=value
print("the dictionary now is :")
print(wins)

PROGRAM NO 2
#program to count the frequency of a list elements using a dictionary
import json
sent="Welcom to the world of computer to the world computer"
words=sent.split()
d={}
for a in words:
key = a
if key not in d:
count=words.count(key)
d[key]=count
print(" counting frequencies in lis\n",words)
print(json.dumps(d,indent = 1))

PROGRAM NO 3
#WAP that takes a value and checks whether the given value is part of
#given dictionary or not. if it is, it should print the corresponding key
#otherwise print an error message
dict1={0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five'}
ans="y"
while ans=='y' or ans=='Y':
val=input("Enter value:")
print("Value",val,end=" ")
for k in dict1:
if dict1[k]==val:
print("exists at",k)
else:
print("not found")
ans=input("want to check more values?(y/n):")

PROGRAM NO 4
#program for demonstrate the use of del and clear()
Dict={'roll':1,'name':'raja','course':'BTech'}
print('Roll number',Dict['roll'])
print('Name:',Dict['name'])
print('course:',Dict['course'])
del Dict['course']#deletes a key value pair
print("After deleting course:",Dict)
Dict.clear()#deletes all entries
print("After clear(), dictionary has no items:",Dict)
del Dict #deletes the variable Dict from memory
print("Dict does not exists......")
print(Dict)

PROGRAM NO 5
#program to randomly pop()or remove an element from a dictionary
def clear():print("\n"*90)
clear()
Dict={'roll':1,'name':'shri','course':'BTech'}
print("name is :",Dict.pop('name'))
print('dictionary after popping name is :',Dict)
print('randomly popping any item:',Dict.popitem())
print('Dictionary after random popping is :',Dict)

PROGRAM NO 6
#WAP that crates two dictionaries. one that stores conversion
#value from meters to centimeters and the other that stores
#from centimeters to meteres
import json
def clear():print('\n'*100)
mtocm={x:x*100 for x in range (1,11)}
temp=mtocm.values()
cmtom={x:x/100 for x in temp}
clear()
print("meters : centimeters",mtocm)
print("centimeters:meters",cmtom)

PROGRAM NO 7
#WAP that creates a dictionary of radius of a circle and its
#circumference
def clear():print('\n'*100)
print ("enter -1 to exit .....")
clear()
cir={}
while True:
r=float(input("enter radius:"))
if r==-1:
break
else:
Dict={r:2*3.14*r}
cir.update(Dict)
clear()
print(cir)
PROGRAM NO 8
#WAP that creates a dictionary of cubes of odd numbers
#in the range 1-10
def clear():print('\n'*100)
Dict = {x:x**3 for x in range(10) if x%2==1}
clear()
print(Dict)

PROGRAM NO 9
#WAP that calculates fib(n) using dictionary
def clear():print('\n'*200)

Dict={0:0,1:1}
def fib(n):
if n not in Dict:
val=fib(n-1)+ fib(n-2)
Dict[n]=val
return Dict[n]
clear()
n=int(input("enter the value of n :"))

print("fib(",n,")=",fib(n))

PROGRAM NO 10
#program to use string formattings features
def clear():print('\n'*10)
Dict={'aman':'Btech','adarsh':'BCA'}
for key,val in Dict.items():
clear()
print("%s is studying %s"%(key,val))

Program no. 11
# a dictionary contains of two emply's details
#name as key and other details and print details
emp={'john':{'age':25,'salary':20000},'aman':{'age':35,'salary':50000}}
for key in emp:
print("employee",key,':')
print('Age:',str(emp[key]['age']))
print('Salary:',str(emp[key]['salary']))

program no. 12
#WAP to create a dictionary containin names of competitions winner student
#as key and number of their wins as values
n=int(input("how many students ?"))
wins={}
for i in range(n):
key=input("name of the student:")
value=int(input("number of competitions won:"))
wins[key]=value
print("the dictionary now is :")
print(wins)
program no. 13
#program to count the frequency of a list elements using a dictionary
import json
sent="Welcom to the world of computer to the world computer"
words=sent.split()
d={}
for a in words:
key = a
if key not in d:
count=words.count(key)
d[key]=count
print(" counting frequencies in lis\n",words)
print(json.dumps(d,indent = 1))

program no. 14
'''WAP that takes a value and checks whether the given value is part of
given dictionary or not. if it is, it should print the corresponding key
otherwise print an error message'''
dict1={0:'zero',1:'one',2:'two',3:'three',4:'four',5:'five'}
ans="y"
while ans=='y' or ans=='Y':
val=input("Enter value:")
print("Value",val,end=" ")
for k in dict1:
if dict1[k]==val:
print("exists at",k)
else:
print("not found")
ans=input("want to check more values?(y/n):")
Program no. 15
#program for demonstrate the use of del and clear()
Dict={'roll':1,'name':'raja','course':'BTech'}
print('Roll number',Dict['roll'])
print('Name:',Dict['name'])
print('course:',Dict['course'])
del Dict['course']#deletes a key value pair
print("After deleting course:",Dict)
Dict.clear()#deletes all entries
print("After clear(), dictionary has no items:",Dict)
del Dict #deletes the variable Dict from memory
print("Dict does not exists......")
print(Dict)
Program no. 16
#program to randomly pop()or remove an element from a dictionary
def clear():print("\n"*1)
clear()
Dict={'roll':1,'name':'shri','course':'BTech'}
print("name is :",Dict.pop('name'))
print('dictionary after popping name is :',Dict)
print('randomly popping any item:',Dict.popitem())
print('Dictionary after random popping is :',Dict)

Program no. 17
'''WAP that crates two dictionaries. one that stores conversion
value from meters to centimeters and the other that stores
from centimeters to meteres'''
import json
def clear():print('\n'*100)
mtocm={x:x*100 for x in range (1,11)}
temp=mtocm.values()
cmtom={x:x/100 for x in temp}
clear()
print("meters : centimeters",mtocm)
print("centimeters:meters",cmtom)

Program no. 18
'''WAP that creates a dictionary of radius of a circle and its
circumference'''
def clear():print('\n'*1)
print ("enter -1 to exit .....")
clear()
cir={}
while True:
r=float(input("enter radius:"))
if r==-1:
break
else:
Dict={r:2*3.14*r}
cir.update(Dict)
clear()
print(cir)
Program no. 19
'''WAP that creates a dictionary of cubes of odd numbers
in the range 1-10'''
def clear():print('\n'*1)
Dict = {x:x**3 for x in range(10) if x%2==1}
clear()
print(Dict)

Program no. 20
#program to use string formattings features
def clear():print('\n'*1)
Dict={'aman':'Btech','adarsh':'BCA'}
for key,val in Dict.items():
clear()
print("%s is studying %s"%(key,val))

Program no. 21
#wap that inverts a dictionary ie.it makes key of one dictionary
# value of another and vice versa
def cls():print('\n'*1)
Dict={'roll':1,'name':'shri','course':'Mtech'}
inverted={}
for key,val in Dict.items():
inverted[val]=key
cls()
print("Dict:",Dict)
print("Inverted Dict:",inverted)
Program no. 22
'''Wap that has dictionary of name of students and a list of
their marks in 4 subjects. Creates another dictionay from this
dictionary that has name of the students and their total marks
find out the topper and his/her score.'''
import json
def cls():print('\n'*1)
marks={'manas':[97,89,94,90],'mehak':[99,93,89,92],'atul':[98,99,90,92]}
tot=0
totmarks=marks.copy()
for key,val in marks.items():
tot = sum(val)
totmarks[key]=tot
cls()
print(json.dumps(totmarks,indent=5))
maxi=0
topper=' '
for key,val in totmarks.items():
if val>maxi:
maxi=val
topper=key
print("Topper is:",topper,"with marks =",maxi)
Program no. 23
'''Wap that print a histogram of frequencies of characters'''
import json
def cls():print('\n'*10)
msg="raja rani"
msg =msg.upper()
Dict=dict()
for word in msg:
if word not in Dict:
Dict[word]=1
else:
Dict[word]=Dict[word]+1
cls()
print(json.dumps(Dict,indent=10))

Program no. 24
''' program for accessing each elements of a dictionary '''
d={1:'one',2:'two',3:'three',4:'four'}
for i in d:
print(i,':',d[i])

Program no. 25
'''program to input total number of sections and stream name in 12th class and display
all information on the output'''
class12=dict()
n=int(input('enter total number of sections in 12th class'))
i=1
while i<=n:
a=input('enter section:')
b=input('enter stream name:')
class12[a]=b
i=i+1
print('Class','\t','section','\t','stream name')
for i in class12:
print('XII','\t',i,'\t',class12[i])
program no. 26
''' program for appending values to a dictionary '''
d1={'mon':'monday','tue':'tuesday','wed':'wednesday'}
d1['thu']='thursday'
print(d1)

Program no.27

''' program for updating elements in a dictionary '''


d1={'raja':40,'rani':30,'mantri':45,'sipahi':65}
print('dictionary befor updating',d1)
d1['sipahi']=35
print('dictionary after updating',d1)
d2={1:10,2:20,3:30,4:40}
print('values of dictionary d2',d2)
d3={5:50,6:60,7:70,8:80}
print('values of dictionary d3',d3)
d2.update(d3)
print('values after updating dictionary',d2)

Program no. 28
''' program for removing item from dictionary using del() and pop() and in and not in
memebership operator '''
a={'mon':'monday','tue':'tuesday','wed':'wednesday','thu':'thursday'}
print('dictionary before removing item ',a)
del a['wed']
print('dictionary after removing item',a)
b={'mon':'monday','tue':'tuesday','wed':'wednesday','thu':'thursday'}
print('dictionary before removing item ',b)
b.pop('tue')
print('dictionary after removing item',b)
print('tue' in b)
print('wed' not in a)

Program no. 29
''' program for common dictionary functions and methods
like len(),clear(),get(),items(),keys(), values()'''
a={1:10,2:20,3:30,4:40}
#len() function returns number of key-values pairs in the dictionary #
print('length of the dictionary is:',len(a))
print(' dictionery values',a)
#clear () removes all the items from the dictioinary#
print('clear function removes all items from the dictionary ',a.clear())
b={'sun':'sunday','mon':'monday','tue':'tuesday'}
#get() returns a value of the given key if the key is not present then returns default value None#
print('get function gets the value of the given key : ',b.get('mon'))
c={'sun':'sunday','mon':'monday','tue':'tuesday','wed':'wednesday','thu':'thursday','fri':'friday'}
print('item of the dictionary',c.items())
# keys() returns a list of the key values in a dictionary#
d={'sun':'sunday','mon':'monday','tue':'tuesday','wed':'wednesday','thu':'thursday','fri':'friday'}
print('keys of the dictionary are:',d.keys())

e={'name':['raja','rani'],'age':[30,25]}
print(e)

You might also like