Python Datatype - Part 5 (Dictionary)
Abdulmutalib Idris
Head of IT and Media / Full Stack Developer @ Agro Preciso LTD
As we learnt earlier Dictionary is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Set.
Example:
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict)
Print the "courses" value of the dictionary:
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict["courses"])
Dictionary Items Are Changeable
We can change, add or remove items after the dictionary has been created.
Duplicates Not Allowed
In Dictionaries duplicated key is not allowed (i.e. two items with the same key). it will not show error when duplication occurs rather the last item will override the earlier once:
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9,
"CGPA": 2.0
}
print(mydict)
Dictionary Length
The len() method is use to determine the number of item in a dictionary
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(len(mydict))
Dictionary Items - Data Types
The values of item in a dictionary can be of any datatype
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9,
"courseList": ["COSC 101", "MATH 102", "ENGL 111", "STAT 112"]
}
print(mydict)
Access Dictionary Items
Accessing Items
To access an item the key of the item will be reference inside square brackets
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict["name"])
The get() method ca also be sue to archive the same result
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict.get("name"))
Get Keys Method
The keys() method will return a list of all the keys in the dictionary.
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict.keys())
Get Values Method
The values() method will return a list of all the values in the dictionary.
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict.values())
Get Items Method
The items() method will return each item in a dictionary, as tuples in a list.
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict.items())
Check if Key Exists
The 'in' keyword is use to check if a key exist in a dictionary
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
if "courses" in mydict:
print("Yes, 'courses' is one of the keys in the mydict dictionary")
Change Dictionary Items
Add New Item
You can add a new item to a dictionary by reference to the key inside square brackets and equating to the value.
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict)
mydict["year"] = 2011;
print(mydict)
Change Values
You can change the value of an item by reference to the key inside square brackets and equating to the new value.
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict)
mydict["courses"] = 11;
print(mydict)
Update Dictionary
update() method can also be use to add item to dictionary and also to update the value of an item with the items from the given argument.
The argument must be a dictionary, or an iterable object with key: value pairs.
领英推荐
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict)
mydict.update({"courses": 11, "year": 2011})
print(mydict)
Remove Dictionary Items
There are various ways to remove items from a dictionary: pop(), popitem(), clear() methods and del keyword
pop()
Method removes the item with the specified key
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict)
mydict.pop("courses")
print(mydict)
popitem()
Removes the last inserted item
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict)
mydict.popitem()
print(mydict)
clear()
Method empties the dictionary
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict)
mydict.clear()
print(mydict)
del
Keyword removes the item with the specified key
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
print(mydict)
del mydict["CGPA"]
print(mydict)
Note: The del keyword can also delete the dictionary completely (del mydict)
Loop Dictionaries
Dictionary can be loop through to print key, value or both key and value. This can be done in various ways as demonstrated below:
- Print key names one by one
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
for x in mydict:
print(x)
- Print values one by one
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
for x in mydict:
print(mydict[x])
- Print key names one by one using the keys() method
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
for x in mydict.keys():
print(x)
- Print values one by one using the values() method
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
for x in mydict.values():
print(x)
- Print bothe keys and values using the items() method
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
for x, y in mydict.items():
print(x + ":", y)
Copy a Dictionary
copying a dictionary can be done in 2 basic ways:
using copy() method
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
mydict2 = mydict.copy()
print(mydict2)
using the dict() constructor
mydict = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
mydict2 = dict(mydict)
print(mydict2)
Note: doing mydict = mydict2 will not copy mydict to mydict2 rather it will make mydict2 a reference to mydict. meaning that changes made in mydict will automatically be made in mydict2
Nested Dictionaries
This is when a dictionary contain dictionaries
students = {
"student1": {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
},
"student2": {
"id": "ST002",
"name": "Halimat Abdulmutalib",
"courses": 10,
"CGPA": 4.5
},
"student3": {
"id": "ST003",
"name": "Abdulmutalib Idris",
"courses": 9,
"CGPA": 3.0
}
}
print(students)
Optionally it can also be created like this:
student1 = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
student2 = {
"id": "ST002",
"name": "Halimat Abdulmutalib",
"courses": 10,
"CGPA": 4.5
}
student3 = {
"id": "ST003",
"name": "Abdulmutalib Idris",
"courses": 9,
"CGPA": 3.0
}
students = {
"student1": student1,
"student2": student2,
"student3": student3
}
print(students)
Access Items in Nested Dictionaries
Using square brackets:
student1 = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
student2 = {
"id": "ST002",
"name": "Halimat Abdulmutalib",
"courses": 10,
"CGPA": 4.5
}
student3 = {
"id": "ST003",
"name": "Abdulmutalib Idris",
"courses": 9,
"CGPA": 3.0
}
students = {
"student1": student1,
"student2": student2,
"student3": student3
}
print(students["student2"]["name"])
Using loops:
student1 = {
"id": "ST001",
"name": "Aisha Yahaya",
"courses": 9,
"CGPA": 3.9
}
student2 = {
"id": "ST002",
"name": "Halimat Abdulmutalib",
"courses": 10,
"CGPA": 4.5
}
student3 = {
"id": "ST003",
"name": "Abdulmutalib Idris",
"courses": 9,
"CGPA": 3.0
}
students = {
"student1": student1,
"student2": student2,
"student3": student3
}
for x in students:
for y in students[x]:
print(students[x][y])
Head of IT and Media / Full Stack Developer @ Agro Preciso LTD
1 年I thought so too. Thank you for always following the class and sharing your thoughts
????? ??????? ??????? ??????? ?? ????? ? ??????? ???? ??? ??????? ??????.
1 年Most beautiful of all the data structures so far!