Comprehensive Guide to Python Dictionaries
1. What is a Dictionary?
------------------------
A dictionary in Python is a collection of unordered, mutable, and indexed k
Each key-value pair is separated by a colon (:) and each pair is separated b
Syntax:
--------
my_dict = {
"name": "John",
"age": 30,
"city": "New York"
}
Key Features:
--------------
1. Unordered
2. Mutable
3. Indexed
4. Keys must be immutable
2. Accessing Items in a Dictionary
----------------------------------
- Using Keys:
my_dict["name"] -> 'John'
- Using get():
my_dict.get("age") -> 30
my_dict.get("gender", "Not Available") -> 'Not Available'
3. Modifying Items
------------------
- Change Value:
my_dict["age"] = 31
- Using update():
my_dict.update({"age": 32})
4. Adding Items
---------------
my_dict["gender"] = "Male"
5. Removing Items
-----------------
- del:
del my_dict["city"]
- pop():
my_dict.pop("age")
- popitem():
my_dict.popitem()
6. Dictionary Methods
----------------------
- keys(), values(), items()
- clear(), copy(), fromkeys()
7. Practical Use Cases
-----------------------
- Counting frequencies of items in a list
- Contact book
- API response storage
8. Advanced Operations
-----------------------
- Nested dictionaries
- Dictionary comprehension
- Merging dictionaries