
Python's dict() Function
The dict() function in Python is a fundamental tool for creating dictionaries, which are unordered collections of key-value pairs.
my_dictionary = dict(key1=value1, key2=value2, ...)
Each entry in a dictionary is uniquely identified by its key, with a corresponding value.
It's crucial to assign a distinct value to every key, and remember that keys must be unique within a dictionary.
An empty dictionary can be initiated by simply using dict() without any arguments.
Let's delve into a practical example:
Starting with an empty dictionary:
my_dictionary = dict()
This step initializes an empty container named my_dictionary. Imagine it as an empty box, ready to be filled.
Consider creating a dictionary to represent a student's details.
student = dict(name="Marco", age=21)
This dictionary now stores two key-value pairs: Marco's name and age.
Each dictionary entry comprises a key (e.g., name and age) and its associated value ("Marco" and 21).
To access a specific piece of information, like the student's name:
print(student["name"])
This command reveals the value linked to the key "name":
Marco
Use square brackets with the key to retrieve its value.
Add more information to the dictionary, such as the student's major:
student["major"] = "Computer Science"
Display the updated dictionary:
print(student)
The dictionary now includes the student's major.
{'name': 'Marco', 'age': 21, 'major': 'Computer Science'}
To remove an entry, like age, the del command comes into play.
For instance, to remove the "age" key:
del student["age"]
This action deletes the age information from the dictionary.
print(student)
{'name': 'Marco', 'major': 'Computer Science'}
Dictionaries in Python are versatile. You can freely add, delete, or alter elements.
Bear in mind that each key is unique. Adding an existing key updates its value with the new input.
Another practical example is creating a store inventory:
Suppose you are setting up an inventory for your store:
inventory = dict(pens=15, notebooks=10, erasers=5)
print(inventory)
Update the inventory as stock changes. For example, if you receive additional pens:
inventory["pens"] = 20.
If erasers are out of stock, remove them:
del inventory["erasers"].
This overview provides a comprehensive understanding of Python's dict() function.
Effectively, managing a dictionary is akin to handling a box: filling it, using its contents, and occasionally discarding unnecessary items.