You are on page 1of 16

PYTHON DICTIONARIES

A python dictionary is a collection of elements where each


element is a combination of Key-Value pair. Each value/values is
associated with a unique key. All the Key-Value pairs are enclosed
in Curly braces. In other words we can say that ” Dictionaries are
mutable, unordered collection of elements in the form of Key-
Value Pairs which are enclosed in curly braces“

Example of Dictionary:
A = {1 : “One”, 2 : “Two”, 3 : “Three”}
B = {“A” : “Apple”, “B” : “Ball”, “C” : “Cat”}
Dictionary A has numeric Keys (1, 2, 3)and Values(“One”, “Two”, “Three” )
are in String, while dictionary B has both Keys(‘A’, ‘B’, ‘C’) and
Values(“Apple”, “Ball”, “Cat”) are in string.

DICT REPRESENTS WORD(KEYS) : MEANING(VALUES)


DECLARING A DICTIONARY
•In a dictionary, all the items are separated by comma and the
entire dictionary is enclosed in curly braces { }.
•Each item consists of two parts – key and a value, separated by a
colon (:).
•Keys are unique in dictionary. They must be of an immutable
data types such as strings, numbers or tuples.
•The values may have duplicate values. They can be of any type.

d1 = {‘amit’: 12, ‘deepak’:32}


d2 = {(‘amit’, 45, 32): [56, 23, 23 66, 77]}
d3 = {1:’sonia’, 2:’monica’}
d4 = { 1: (‘deepak’, 65), 2: (‘divya’, 89)}
employee={"Shikha":"Programmer","Pooja","Teacher"}
print (employee)
CREATING EMPTY DICTIONARY USING dict() KEYWORD
weekdays = dict() # creating blank / empty dict
print (weekdays)
weekdays = { } # creating blank / empty dict
weekdays[0] = 'sunday‘ #adding key-value pair to dict.
weekdays[1] = 'monday'
weekdays[2] = 'tuesday'
print (weekdays)
ADDING A KEY AND VALUES TO DICTIONARY
employee['Dipak']='engineer'
print (employee)
Ques – create a dictionary to store details of 5 friends of your where
Mobile number is the key and name is the value. And then display these details.
DELETE A KEY AND VALUES TO DICTIONARY
del employee['Dipak']='Principal'
print (employee)

TRAVERSING /PRINT TO DICTIONARY


for E in employee:
     print (E,":",employee[E])

DICTIONARY FUNCTIONS
marks={"priyesh":450,"paras":560","chandni":490,"rachit":400}
print "Total number of key-value pairs in the dictionary are ",len(marks)
WAP TO STORE DETAIL OF 5 STUDENTS HAVING THEIR ROLL AND
MARKS AS KEY VALUE PAIR IN A DICT AND THE DISPLAY THE DETAILS
ALONG WITH THE AVERAGE MARKS OF THIS CLASS
mk={}
for i in range(1,6):
k=int(input("enter marks "))
mk[i]=k
print(mk)
s=0
av=0
for i in mk:
print(i,"roll no having ",mk[i]," marks")
s=s+mk[i]
print("total marks of the class ",s)
av=s/len(mk)
print("average marks ",av)
WAP TO CREATE A DICTIONARY OF WEEKDAYS WHERE
FIND THE OUTPUT SHORT NAME OF THE WEEK IS THE KEY AND FULL
a = {i: i * i for i in range(6)} NAME IS THE VALUES AND PRINT ALL THE KEYS AND
VALUES SEPARATELY
print (a) OF THIS DICTIONARY

day={"sun":"sunday","mon":"monday","tue":"t
uesday","wed":"wednesday","thu":"thursday","

a ={} fri":"friday","sat":"saturday"}
print("details ")
dict = a.fromkeys(['a', 'b', 'c', 'd'], 98)
print(day)
print (a)
print()
print (dict)
print("all keys of the dictionary ")
print(day.keys())
print()
print("all values of the dictionary ")
print(day.values())
Explanation: fromkeys() create a new
dictionary with keys from list given to
it as an argument and set values of the
key, the default value given in it as an
argument.
FIND THE OUTPUT
dictionary1 = {'Google' : 1,
'Facebook' : 2,
'Microsoft' : 3
}
dictionary2 = {'GFG' : 1,
'Microsoft' : 2,
'Youtube' : 3
}
dictionary1.update(dictionary2);
for key, values in dictionary1.items(): Explanation:
print(key, values) dictionary1.update(dictionary2) is
used to update the entries of
dictionary1 with entries of
dictionary2. If there are same keys
in two dictionaries, then the value
in second dictionary is used.
FIND THE OUTPUT
test = {1:'A', 2:'B', 3:'C'}
del test[1]
test[1] = 'D'
del test[2]
print(len(test))

d1={1:'ONE',2:'TWO',3:'THREE',4:'FOUR'}
d2={5:"FIVE",6:"SIX"}
print(d1.items())
print(d1.keys())
d1.update(d2)
print(len(d1))
FIND THE OUTPUT
FIND THE OUTPUT
d1={1:'ONE',2:'TWO',3:'THREE',4:'FOUR'}
d2={5:"FIVE",6:"SIX"}
del d1[3]
print(d1)
d1.pop(4)
print(d1)
d1[8]="EIGHT"
print(d1)
d1.clear()
print(d1)

d={(1,2):1,(2,3):2}
print(d[1,2])
d={'a':1,'b':2,'c':3}
print(d['a'])
print(d['b'])
WAP TO STORE DETAILS OF 6 PRODUCTS IN A DICTIONARY WHERE PRODUCT NO IS
THE KEY AND THEIR PRICE IS A VALUE. THEN DISPLAY THE DETAILS OF THIS
DICTIONARY ALONG WITH THE MAXIMUM PRICE AND TOTAL PRICE

p={} enter product no 10


for i in range(1,6): enter price 200
pn=int(input("enter product no ")) enter product no 11
pr=int(input("enter price ")) enter price 300
p[pn]=pr enter product no 12
print("details od dictionary ") enter price 555
enter product no 13
print(p)
enter price 125
mx=0 enter product no 14
s=0 enter price 100
for i in p: details od dictionary
if p[i]>mx: {10: 200, 11: 300, 12: 555, 13: 125, 14: 100}
mx=p[i] maximum price 555
s=s+p[i] total price 1055
print("maximum price ",mx)
write a python program to create a dictionary
on the basic of the following table
bno bname subject price pages

1001 flamingo english 50 209

2002 subhash dey eco 250 287

3003 ncert maths 100 225

4004 vistas english 75 150

5005 sumit arora ip 240 354

dc={'bno':[1001,2002,3003,4004,5005],
'bname':["flamingo","subhash dey","ncert","vistas","sumit arora"],
'subject':["english","eco","maths","english","ip"],
'price':[50,250,100,75,240],
'pages':[209,287,225,150,354]}
print(dc)

Now add a new column with the name copies in the above
dictionary
dc["copies"]=[10,20,15,20,30]
print(dc)

Display all the column headings of the table


print(dc.keys())
WAP TO CREATE A DICT. FOR 5 FRUITS WHERE KEY WAP TO CREATE A DICT. FOR FIRST 6
IE FRUITS CODE IS FIRST CHAR OF FRUIT NAME MONTHS OF THE YEAR AND NUMBER
AND VALUE IS FRUIT NAME, OBTAIN FROM THE OF DAYS FOR A YEAR. USER IS ASKED
USER. THEN POP THE 3RD ELEMENT FROM THIS TO ENTER MONTH NAME AND SYSTEM
DICTIONARY AND ADD THIS ELEMENT TO A NEW WILL DISPLAY DAYS IN IT.
DICTIONARY

f={}
c=0
for i in range(1,5):
code=input("enter fruit code ")
name=input("enter fruits name ")
f[code]=name
c=c+1
if c==3:
cr=code
bn=name
print(f)
n=f.pop(cr)
print(n)
k={}
k[cr]=bn
print(k)
'''WAP TO CREATE A DICT.
FROM THE STRING
"COMPUTER" SUCH THAT
EACH INDIVIDUAL
CHARACTER MAKES A KEY
AND ITS INDEX VALUE
BECOME VALUES FOR THE d={0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five"
DIC. ,6:"six",7:"seven",8:"eight",9:"nine"}
''' print(d)
d={} n=int(input("enter a number "))
s="computer" l=[]

l=len(s) while n!=0:


for i in range(0,l): r=n%10
l.append(r)
d[s[i]]=i n=n//10
print(d) print(l)
l.reverse()
for k in l:
for i in d:
if k==i:
print(d[i],end =" ")

You might also like