SlideShare a Scribd company logo
Dictionaries
Python Dictionary
• The dictionary itself is an abstract datatype.
• In this it contains a group of data with the different data types.
• And each data is stored as a key-value pair, that key is used to
identify that data.
• We can add or replace values of the dictionary, it is mutable.
• But the key associated with the dictionary can't be changed.
• Therefore, the keys are immutable or unique.
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
keys( )
values()
items()
The syntax provides useful type information. The square brackets indicate that it’s a
list. The parenthesis indicate that the elements in the list are tuples.
2 UNIT CH3 Dictionaries v1.ppt
Aliasing and copy using function- copy()
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
QUIZ
Which of the following statements create a
dictionary?
a) d = {}
b) d = {“john”:40, “peter”:45}
c) d = {40:”john”, 45:”peter”}
d) All of the mentioned
Items are accessed by their position in a dictionary
and All the keys in a dictionary must be of the same
type.
a. True
b. False
Dictionary keys must be immutable
a. True
b. False
In Python, Dictionaries are immutable
a. True
b. False
What will be the output of the following Python code snippet?
a={1:"A",2:"B",3:"C"}
for i,j in a.items():
print(i,j,end=" ")
a) 1 A 2 B 3 C
b) 1 2 3
c) A B C
d) 1:”A” 2:”B” 3:”C”
Select the correct way to print Emma’s age.
student = {1: {'name': 'Emma', 'age': '27', 'sex': 'Female'},
2: {'name': 'Mike', 'age': '22', 'sex': 'Male'}}
a. student[0][1]
b. student[1]['age']
c. student[0]['age']
d. student[2]['age']
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
Fibonacci using Dictionary
fib={0:0,1:1}
def fibo(n):
if(n==0):
return 0
if(n==1):
return 1
else:
for i in range(2, n+1):
fib[i]=fib[i-1]+fib[i-2]
return(fib)
print(fibo(5))
Use get()
The get() method returns the value of the item with the specified key.
Syntax:
dictionary.get(keyname, value)
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
Iterate over Python dictionaries using for loops
d={'red':1,'green':2,'blue':3}
for color_key, value in d.items():
print(color_key,'corresponds to', d[color_key])
OUTPUT:
blue corresponds to 3
green corresponds to 2
red corresponds to 1
Remove a key from a Python dictionary
myDict = {'a':1,'b':2,'c':3,'d':4}
print(myDict)
if 'a' in myDict:
del myDict['a']
print(myDict)
OUTPUT:
{'d': 4, 'a': 1, 'b': 2, 'c': 3}
{'d': 4, 'b': 2, 'c': 3}
Sort a Python dictionary by key
color_dict = {'red':'#FF0000',
'green':'#008000',
'black':'#000000',
'white':'#FFFFFF‘
}
for i in sorted(color_dict):
print(key,” :”, color_dict[ i ]))
OUTPUT:
black: #000000
green: #008000
red: #FF0000
white: #FFFFFF
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
• Use update() on dictionary
• The pop() method removes the specified item from the dictionary.
• The popitem() method removes the item that was last inserted into
the dictionary. In versions before 3.7, the popitem() method removes
a random item.
Find the maximum and minimum value of a Python dictionary
2 UNIT CH3 Dictionaries v1.ppt
Concatenate two Python dictionaries into a new one
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for d in (dic1, dic2, dic3):
dic4.update(d)
print(dic4)
OUTPUT:
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
Test whether a Python dictionary contains a specific key
fruits = {}
fruits["apple"] = 1
fruits["mango"] = 2
fruits["banana"] = 4
if "mango" in fruits:
print("Has mango")
else:
print("No mango")
if "orange" in fruits:
print("Has orange")
else:
print("No orange")
OUTPUT:
Has mango
No orange
QUESTIONS
Q1:Write a Python script to add a key to a dictionary.
Sample Dictionary : {0: 10, 1: 20}
Expected Result : {0: 10, 1: 20, 2: 30}
Q2: Write a Python script to concatenate following dictionaries to create a new one.
Sample Dictionary :
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
Q3: Write a Python script to check if a given key already exists in a dictionary.
Q4: Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and
the values are square of keys.
Sample Dictionary
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
• #Add two dictionaries and get
results.
• #concatenate dictionaries
• d1={'A':1000,'B':2000}
• d2={'C':3000}
• d1.update(d2)
• print("Concatenated dictionary is:")
• print(d1)
• o/p: Concatenated dictionary is:
• {'A': 1000, 'B': 2000, 'C': 3000}
#concatenate dictionaries
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for i in (dic1, dic2, dic3):
dic4.update(i)
print(dic4)
o/p:
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
#Q3: Write a Python script to check if a given key already
exists in a dictionary.
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
def present(i):
if i in d:
print(i ,' key is present in the dictionary')
else:
print(i, 'key is not present in the dictionary')
present(20)
present(3)
o/p:
20 key is not present in the dictionary
3 key is present in the dictionary
##sum and multiplication of dictionary
elements
d = {1: 10, 2: 20, 3: 1, 4: 1, 5: 1, 6: 1}
print(sum(d.values()))
mul=1
for i in d:
mul = mul * d[i]
print("Multiplication is", mul)
#
Use of __setitem__ ( )
• myDict = {1:100, 2:200}
• myDict.__setitem__(33,300)
• myDict
• {1: 100, 2: 200, 33: 300}
Add user input() in a dictionary
• d = { }
• for i in range(3):
– i = input(“enter Key")
– j = input(“enter value")
– d[i] = j
print(d)
Take dictionary items() from user
Q6: Write a Python script to merge two Python dictionaries.
Q7: Write a Python program to sum all the items in a dictionary.
Q8: Write a Python program to multiply all the items in a dictionary.
Q9: Write a Python program to remove a key from a dictionary.
Q10: Write a Python program to remove duplicates from Dictionary.
Q11: Write a Python program to create and display all combinations of letters, selecting each letter from a
different key in a dictionary.
Sample data : {'1':['a','b'], '2':['c','d']}
Expected Output:
ac
ad
bc
bd
Q9: Write a Python program to remove a key from
a dictionary.
• d = {'a':100, 'b':200, 'c':300, 'd':400}
• del d['a']
• >>>d
• {'b': 200, 'c': 300, 'd': 400}
2 UNIT CH3 Dictionaries v1.ppt
# Use function and print players details of a dictionary
def indian_cricket(d):
for i in d:
print("Details of Players are", d[i])
ind = {'test1':{'Dhoni':75, 'Kohli':170 }, 'test2':{'Dhoni':30, 'Pujara': 45} }
indian_cricket(ind)
o/p
Details of Players are {'Dhoni': 75, 'Kohli': 170}
Details of Players are {'Dhoni': 30, 'Pujara': 45}
• Define a python function ‘indian_cricket(d)’ which reads a dictionary
of the following form and identifies the player with the highest total
score. The function should return a pair (, topscore), where
playername is the name of the player with the highest score and
topscore is the total runs scored by the player.
Input is:
indian_cricket (
{‘test1’:{‘Dhoni’:75, ‘Kohli’:170},
‘test2’:{Dhoni’: 30, ‘Pujara’: 45}
})
Solution:
• maxdic={}
• dic={'test1':{'Dhoni':75, 'Kohli':170 },
• 'test2':{'Dhoni':30, 'Pujara': 45}
• }
• for keymain,valuemain in dic.items(): #keymain is test1 , test ... keys
• max=0
• key1=''
• dicin={}
• for key,value in valuemain.items():
• if(value>max):
• max=value
• key1=key
• dicin[key1]=max #key1 is used for Dhoni, kohli, Pujara
• maxdic[keymain]=dicin
• print("Topscore Player wise in different Tests is", maxdic)

More Related Content

PPTX
Farhana shaikh webinar_dictionaries
PDF
Lecture-6.pdf
PPTX
Chapter 16 Dictionaries
PDF
"Python Dictionary: The Key to Efficient Data Storage, Manipulation, and Vers...
PPTX
DICTIONARIES TUTORIALS FOR ADVANCED LEARNING OF YTHON PROGRAMMING
PPTX
Chapter 14 Dictionary.pptx
PPTX
Dictionariesasdfghjsdfghjklsdfghjkl.pptx
PPTX
Dictionary in python
Farhana shaikh webinar_dictionaries
Lecture-6.pdf
Chapter 16 Dictionaries
"Python Dictionary: The Key to Efficient Data Storage, Manipulation, and Vers...
DICTIONARIES TUTORIALS FOR ADVANCED LEARNING OF YTHON PROGRAMMING
Chapter 14 Dictionary.pptx
Dictionariesasdfghjsdfghjklsdfghjkl.pptx
Dictionary in python

Similar to 2 UNIT CH3 Dictionaries v1.ppt (20)

PPTX
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
PPT
Dictionarys in python programming language.ppt
PPTX
dictionary14 ppt FINAL.pptx
PPTX
Untitled dictionary in python program .pdf.pptx
PPTX
Dictionaries in Python programming language
PPTX
Ch 7 Dictionaries 1.pptx
PPTX
Python-Dictionaries.pptx easy way to learn dictionaries
PDF
Dictionaries in Python programming for btech students
PDF
Python dictionaries
PPTX
Meaning of Dictionary in python language
PPTX
Python programming –part 7
PDF
Python Dictionary
PPTX
ch 13 Dictionaries2.pptx
PPTX
Python dictionary
PPTX
python advanced data structure dictionary with examples python advanced data ...
PPTX
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
PPTX
Dictionaries and Sets
PPTX
Ch_13_Dictionary.pptx
PPTX
6Dictionaries and sets in pythonsss.pptx
PPTX
Week 10.pptx
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
Dictionarys in python programming language.ppt
dictionary14 ppt FINAL.pptx
Untitled dictionary in python program .pdf.pptx
Dictionaries in Python programming language
Ch 7 Dictionaries 1.pptx
Python-Dictionaries.pptx easy way to learn dictionaries
Dictionaries in Python programming for btech students
Python dictionaries
Meaning of Dictionary in python language
Python programming –part 7
Python Dictionary
ch 13 Dictionaries2.pptx
Python dictionary
python advanced data structure dictionary with examples python advanced data ...
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
Dictionaries and Sets
Ch_13_Dictionary.pptx
6Dictionaries and sets in pythonsss.pptx
Week 10.pptx
Ad

Recently uploaded (20)

PDF
Complications of Minimal Access Surgery at WLH
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
01-Introduction-to-Information-Management.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
Cell Types and Its function , kingdom of life
PDF
Computing-Curriculum for Schools in Ghana
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Presentation on HIE in infants and its manifestations
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
Complications of Minimal Access Surgery at WLH
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
01-Introduction-to-Information-Management.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
2.FourierTransform-ShortQuestionswithAnswers.pdf
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
Chinmaya Tiranga quiz Grand Finale.pdf
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Cell Types and Its function , kingdom of life
Computing-Curriculum for Schools in Ghana
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
Final Presentation General Medicine 03-08-2024.pptx
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Supply Chain Operations Speaking Notes -ICLT Program
GDM (1) (1).pptx small presentation for students
Presentation on HIE in infants and its manifestations
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Final Presentation General Medicine 03-08-2024.pptx
Ad

2 UNIT CH3 Dictionaries v1.ppt

  • 2. Python Dictionary • The dictionary itself is an abstract datatype. • In this it contains a group of data with the different data types. • And each data is stored as a key-value pair, that key is used to identify that data. • We can add or replace values of the dictionary, it is mutable. • But the key associated with the dictionary can't be changed. • Therefore, the keys are immutable or unique.
  • 9. The syntax provides useful type information. The square brackets indicate that it’s a list. The parenthesis indicate that the elements in the list are tuples.
  • 11. Aliasing and copy using function- copy()
  • 14. QUIZ
  • 15. Which of the following statements create a dictionary? a) d = {} b) d = {“john”:40, “peter”:45} c) d = {40:”john”, 45:”peter”} d) All of the mentioned
  • 16. Items are accessed by their position in a dictionary and All the keys in a dictionary must be of the same type. a. True b. False
  • 17. Dictionary keys must be immutable a. True b. False
  • 18. In Python, Dictionaries are immutable a. True b. False
  • 19. What will be the output of the following Python code snippet? a={1:"A",2:"B",3:"C"} for i,j in a.items(): print(i,j,end=" ") a) 1 A 2 B 3 C b) 1 2 3 c) A B C d) 1:”A” 2:”B” 3:”C”
  • 20. Select the correct way to print Emma’s age. student = {1: {'name': 'Emma', 'age': '27', 'sex': 'Female'}, 2: {'name': 'Mike', 'age': '22', 'sex': 'Male'}} a. student[0][1] b. student[1]['age'] c. student[0]['age'] d. student[2]['age']
  • 23. Fibonacci using Dictionary fib={0:0,1:1} def fibo(n): if(n==0): return 0 if(n==1): return 1 else: for i in range(2, n+1): fib[i]=fib[i-1]+fib[i-2] return(fib) print(fibo(5))
  • 24. Use get() The get() method returns the value of the item with the specified key. Syntax: dictionary.get(keyname, value)
  • 27. Iterate over Python dictionaries using for loops d={'red':1,'green':2,'blue':3} for color_key, value in d.items(): print(color_key,'corresponds to', d[color_key]) OUTPUT: blue corresponds to 3 green corresponds to 2 red corresponds to 1 Remove a key from a Python dictionary myDict = {'a':1,'b':2,'c':3,'d':4} print(myDict) if 'a' in myDict: del myDict['a'] print(myDict)
  • 28. OUTPUT: {'d': 4, 'a': 1, 'b': 2, 'c': 3} {'d': 4, 'b': 2, 'c': 3} Sort a Python dictionary by key color_dict = {'red':'#FF0000', 'green':'#008000', 'black':'#000000', 'white':'#FFFFFF‘ } for i in sorted(color_dict): print(key,” :”, color_dict[ i ])) OUTPUT: black: #000000 green: #008000 red: #FF0000 white: #FFFFFF
  • 31. • Use update() on dictionary
  • 32. • The pop() method removes the specified item from the dictionary. • The popitem() method removes the item that was last inserted into the dictionary. In versions before 3.7, the popitem() method removes a random item.
  • 33. Find the maximum and minimum value of a Python dictionary
  • 35. Concatenate two Python dictionaries into a new one dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} dic4 = {} for d in (dic1, dic2, dic3): dic4.update(d) print(dic4) OUTPUT: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
  • 36. Test whether a Python dictionary contains a specific key fruits = {} fruits["apple"] = 1 fruits["mango"] = 2 fruits["banana"] = 4 if "mango" in fruits: print("Has mango") else: print("No mango") if "orange" in fruits: print("Has orange") else: print("No orange") OUTPUT: Has mango No orange
  • 37. QUESTIONS Q1:Write a Python script to add a key to a dictionary. Sample Dictionary : {0: 10, 1: 20} Expected Result : {0: 10, 1: 20, 2: 30} Q2: Write a Python script to concatenate following dictionaries to create a new one. Sample Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} Q3: Write a Python script to check if a given key already exists in a dictionary. Q4: Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys. Sample Dictionary {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
  • 38. • #Add two dictionaries and get results. • #concatenate dictionaries • d1={'A':1000,'B':2000} • d2={'C':3000} • d1.update(d2) • print("Concatenated dictionary is:") • print(d1) • o/p: Concatenated dictionary is: • {'A': 1000, 'B': 2000, 'C': 3000} #concatenate dictionaries dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60} dic4 = {} for i in (dic1, dic2, dic3): dic4.update(i) print(dic4) o/p: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
  • 39. #Q3: Write a Python script to check if a given key already exists in a dictionary. d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60} def present(i): if i in d: print(i ,' key is present in the dictionary') else: print(i, 'key is not present in the dictionary') present(20) present(3) o/p: 20 key is not present in the dictionary 3 key is present in the dictionary ##sum and multiplication of dictionary elements d = {1: 10, 2: 20, 3: 1, 4: 1, 5: 1, 6: 1} print(sum(d.values())) mul=1 for i in d: mul = mul * d[i] print("Multiplication is", mul) #
  • 40. Use of __setitem__ ( ) • myDict = {1:100, 2:200} • myDict.__setitem__(33,300) • myDict • {1: 100, 2: 200, 33: 300}
  • 41. Add user input() in a dictionary • d = { } • for i in range(3): – i = input(“enter Key") – j = input(“enter value") – d[i] = j print(d)
  • 43. Q6: Write a Python script to merge two Python dictionaries. Q7: Write a Python program to sum all the items in a dictionary. Q8: Write a Python program to multiply all the items in a dictionary. Q9: Write a Python program to remove a key from a dictionary. Q10: Write a Python program to remove duplicates from Dictionary. Q11: Write a Python program to create and display all combinations of letters, selecting each letter from a different key in a dictionary. Sample data : {'1':['a','b'], '2':['c','d']} Expected Output: ac ad bc bd
  • 44. Q9: Write a Python program to remove a key from a dictionary. • d = {'a':100, 'b':200, 'c':300, 'd':400} • del d['a'] • >>>d • {'b': 200, 'c': 300, 'd': 400}
  • 46. # Use function and print players details of a dictionary def indian_cricket(d): for i in d: print("Details of Players are", d[i]) ind = {'test1':{'Dhoni':75, 'Kohli':170 }, 'test2':{'Dhoni':30, 'Pujara': 45} } indian_cricket(ind) o/p Details of Players are {'Dhoni': 75, 'Kohli': 170} Details of Players are {'Dhoni': 30, 'Pujara': 45}
  • 47. • Define a python function ‘indian_cricket(d)’ which reads a dictionary of the following form and identifies the player with the highest total score. The function should return a pair (, topscore), where playername is the name of the player with the highest score and topscore is the total runs scored by the player. Input is: indian_cricket ( {‘test1’:{‘Dhoni’:75, ‘Kohli’:170}, ‘test2’:{Dhoni’: 30, ‘Pujara’: 45} })
  • 49. • maxdic={} • dic={'test1':{'Dhoni':75, 'Kohli':170 }, • 'test2':{'Dhoni':30, 'Pujara': 45} • } • for keymain,valuemain in dic.items(): #keymain is test1 , test ... keys • max=0 • key1='' • dicin={} • for key,value in valuemain.items(): • if(value>max): • max=value • key1=key • dicin[key1]=max #key1 is used for Dhoni, kohli, Pujara • maxdic[keymain]=dicin • print("Topscore Player wise in different Tests is", maxdic)