Python Dictionaries
What is a Python Dictionary?
A Python dictionary is an unordered collection that stores data as key-value pairs. Each key is unique, and each key maps to a value. You can use the key to access the associated value. Think of it as a real-world dictionary where you look up a word (key) and get its meaning (value).
Example of a Dictionary
my_dict = {
"name": "Arjun",
"age": 25,
"city": "New York"
}
In this dictionary, the keys are "name", "age", and "city". The corresponding values are "Arjun", 25, and "New York".
Where Are Dictionaries Used?
Dictionaries are very useful when you need to store data that is associated with a unique identifier (the key). For example, storing student names with their grades, a person's contact information (name, phone number, etc.), or the countries and their capitals.
Basic Operations on Dictionaries
1. Create a Dictionary
To create a dictionary, you can use curly braces {} and separate keys and values with a colon :.
student = {
"name": "Arjun",
"age": 22,
"grade": "A"
}
2. Read/Access Data
To get the value associated with a key, you can use square brackets [] with the key.
student = {
"name": "Arjun",
"age": 22,
"grade": "A"
}
print(student["name"])
Arjun
3. Update Data
If you want to change the value associated with a key, you can directly assign a new value to that key.
student = {
"name": "Arjun",
"age": 22,
"grade": "A"
}
student["age"] = 23
print(student)
{'name': 'Arjun', 'age': 23, 'grade': 'A'}
4. Add New Key-Value Pair
You can add a new key-value pair to the dictionary by assigning a value to a new key.
student = {
"name": "Arjun",
"age": 22,
"grade": "A"
}
student["city"] = "London"
print(student)
{'name': 'Arjun', 'age': 22, 'grade': 'A', 'city': 'London'}
5. Delete Data
If you want to remove a key-value pair from the dictionary, you can use the del keyword.
student = {
"name": "Arjun",
"age": 22,
"grade": "A"
}
del student["grade"]
print(student)
{'name': 'Arjun', 'age': 22}
Summary of CRUD Operations
- Create:
my_dict = {}to create a dictionary. - Read:
my_dict[key]to access a value by key. - Update:
my_dict[key] = new_valueto update a value. - Add:
my_dict[new_key] = new_valueto add a new key-value pair. - Delete:
del my_dict[key]to delete a key-value pair.
Comments
Loading comments...