π What Is a Dictionary in Python?
A dictionary is a built-in Python data type that stores information in the form of key–value pairs.
It is similar to a real-life dictionary where a word acts as a key and its meaning is the value.
✔ Key Features:
-
Unordered – Items do not have a fixed position.
-
Mutable – You can change, add, or remove items.
-
Key-based access – Values are retrieved using keys, not indexes.
-
No duplicate keys – Each key must be unique
π·️ Creating a Dictionary
Here’s the simplest example:
This dictionary contains three pieces of information (values) associated with their respective keys.
π Accessing Dictionary Values
You can get values by using their key:
If you try to access a non-existent key, Python will raise an error.
π ️ Adding and Updating Items
Dictionaries are flexible—you can add new key–value pairs or update existing ones anytime.
➕ Add a new item
π Update an existing item
π️ Deleting Items From a Dictionary
You can remove items in multiple ways.
Using del
Using pop()
π Looping Through a Dictionary
Loop through both keys and values using .items():
π Nested Dictionaries
Dictionaries can contain other dictionaries—useful for organizing complex data.
This structure is widely used in APIs and JSON data.
π§© Where Are Dictionaries Used?
Python dictionaries are everywhere, especially in:
-
Web development
-
Data analysis
-
Machine learning
-
APIs and JSON
-
Config files
-
Chatbots and NLP
Their power lies in how quickly they retrieve data based on keys.
π Conclusion
Python dictionaries are one of the most useful data structures you will use, thanks to their flexibility and speed. By mastering dictionaries, you can handle real-world data more efficiently and write cleaner, more organized code.
No comments:
Post a Comment