Python Detailed Notes – Dictionaries
1. What is a Dictionary?
A dictionary in Python is a mapping data type that stores data in key–value pairs. Keys are unique
and separated from values by a colon (:). Items are separated by commas. Dictionaries are
unordered before Python 3.7 but maintain insertion order from Python 3.7 onwards.
2. Properties of Dictionaries
- Keys must be unique and immutable (number, string, tuple).
- Values can be duplicated and of any type.
- Dictionaries are mutable (can be changed).
3. Accessing Items in a Dictionary
Access values by keys: dict[key]. If the key is missing, KeyError occurs. Use get(key) to avoid error.
4. Membership Operators
Use 'in' or 'not in' to check if a key exists in the dictionary.
5. Modifying Dictionaries
- Add item: dict[key] = value
- Modify item: dict[key] = new_value
- Delete item: del dict[key]
- Clear all items: [Link]()
6. Traversing a Dictionary
Method 1: for key in dict → print(key, dict[key])
Method 2: for key, value in [Link]() → print(key, value)
7. Built-in Functions & Methods
len(dict), dict(), keys(), values(), items(), get(key), update(dict2), clear(), del dict[key]
8. Example: Dictionary of Odd Numbers
ODD = {1:'One', 3:'Three', 5:'Five', 7:'Seven', 9:'Nine'}
9. Programs on Dictionaries
- Store Employee Salaries
- Count Occurrences of Characters
- Convert Number to Words
10. Key Points to Remember
- Dictionaries are unordered collections of key-value pairs.
- Keys are unique and immutable.
- Values can be duplicated and mutable.
- Use get() instead of [] to avoid errors.
- Useful methods: keys(), values(), items(), update(), clear().