CRUD Operations on a Dictionary
Create
- A dictionary is created with key-value pairs.
- Keys include name, age, class, and subjects.
student = {'name': 'Tom', 'age': 17, 'class': '24/12', 'subjects': ['math', 'computing', 'physics', 'economics']}
print(student)
---------------------------------------
{'name': 'Tom', 'age': 17, 'class': '24/12', 'subjects': ['math', 'computing', 'physics', 'economics']}
Read
- Access dictionary values using
get() or direct indexing.
get() is safer as it does not throw an error for missing keys.
print(student.get('age')) # Output: 17
print(student.get('id')) # Output: None
---------------------------------------
17
None
Update
- Update values of keys or modify nested elements (e.g., a list inside the dictionary).
student['class'] = '24/13' # Update class
student['subjects'][1] = 'biology' # Update subject
print(student)
---------------------------------------
{'name': 'Tom', 'age': 17, 'class': '24/13', 'subjects': ['math', 'biology', 'physics', 'economics']}
Delete
- Use
del or pop() to remove key-value pairs.
del student['age']
student.pop('subjects')
print(student)
---------------------------------------
{'name': 'Tom', 'class': '24/13'}
Insert
- Add new key-value pairs to the dictionary.
student['teacher'] = 'Mr Tan'
print(student)
---------------------------------------
{'name': 'Tom', 'class': '24/13', 'teacher': 'Mr Tan'}
Dictionary Operations Summary
- Keys: Use
student.keys() to display all keys.
- Values: Use
student.values() to display all values.
- Items: Use
student.items() to get key-value pairs.
- Length: Use
len() to get the size of the dictionary.
print(student.keys())
print(student.values())
print(student.items())
print(len(student))
---------------------------------------
dict_keys(['name', 'class', 'teacher'])
dict_values(['Tom', '24/13', 'Mr Tan'])
dict_items([('name', 'Tom'), ('class', '24/13'), ('teacher', 'Mr Tan')])
3