Dictionary
Python
Programming
Language
Learning Outcome
• To be to understand the features of Dictionary collection.
• To practice coding with Dictionaries in Python programming language.
Introduction
• It is ordered (in version 3.7 onwards), changeable and does not allow duplicates
values.
• Written in curly brackets.
• Have data with key:value pairs.
Sample
Key Value
sampleDict = { "student1": "Feroz “,
“Address": “123, Jalan Tuah“,
“YOB”: 1950
}
print(sampleDict["student1"])
NO Duplicates
sampleDict = { "student1": "Feroz “,
“Address": “123, Jalan Tuah“,
“YOB”: 1950,
“YOB”:2021
}
print(sampleDict)
Print With Key
sampleDict = { "student1": "Feroz “,
“Address": “123, Jalan Tuah“,
“YOB”: 1950
}
z = sampleDict[“Address”]
print(z)
Print List of Keys
sampleDict = { "student1": "Feroz “,
“Address": “123, Jalan Tuah“,
“YOB”: 1950
}
z = sampleDict.keys()
print(z)
Print List of Values
sampleDict = { "student1": "Feroz “,
“Address": “123, Jalan Tuah“,
“YOB”: 1950
}
z = sampleDict.values()
print(z)
Add New Key
sampleDict = { "student1": "Feroz “,
“Address": “123, Jalan Tuah“,
“YOB”: 1950
}
z = sampleDict.keys()
print(z) #BEFORE changes
sampleDict[“Occupation”] = “Lecturer”
print(z) #AFTER the changes
Change the Value
sampleDict = { "student1": "Feroz “,
“Address": “123, Jalan Tuah“,
“YOB”: 1950
}
sampleDict[“YOB”] = 2021
print(sampleDict)
Adding and Update
sampleDict = { "student1": "Feroz “,
“Address": “123, Jalan Tuah“,
“YOB”: 1950
}
sampleDict[“Car”] = “MyVi”
print(sampleDict)
sampleDict = { "student1": "Feroz “,
“Address": “123, Jalan Tuah“,
“YOB”: 1950
}
sampleDict.update({“Car”: “Ativa”})
print(sampleDict)
Loop
sampleDict = { "student1": "Feroz “,
“Address": “123, Jalan Tuah“,
“YOB”: 1950
}
for y, z in sampleDict.items():
print(y,z)
Loop
sampleDict = { "student1": "Feroz “,
“Address": “123, Jalan Tuah“,
“YOB”: 1950
}
for z in sampleDict:
print(sampleDict[z])
Tutorial
• Display your data such as name, course etc. using Dictionary data type and update
any of the data.