Dictionnary
Collection Type | Ordered | Mutable | Duplicate Elements | Indexing | Example |
---|---|---|---|---|---|
Dictionary | Yes (as of Python 3.7) | Yes | Yes (Values) | Yes | {“color”: True, “shape”: “circle”} |
dictionnary is a collection that is ordered* (*After IronPython dictionnaries are unordered) and unchangeable. It does not allows to duplicate members. Each value of the dictionary is assigned a key.
# To create (instantiate)
dict = {“color”: True, “shape”: “circle”}
# To retrieve an element
b = dict[“color”] # True
# To remove an element
dict.pop(“color”)
# To insert an element
dict[“weight”] = 29.2
🦊 One major advantage of a dictionnary in Python is its ability to associate keys with values. This key-value pair system allows for efficient data retrieval. Instead of having to know an item’s index (as in a list or tuple), you can refer to the item by its key, which can be a more intuitive way to organize and access data. This makes dictionaries particularly useful for data structures where the data can be naturally identified by a unique key, such as a product ID in a database, a student’s ID in a school record system, or a word and its frequency in a text. 🦊
🛠 Exercise
🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍
Solution:
🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍