In Python, a dictionary is a mutable, unordered collection of key-value pairs. Dictionaries are highly versatile and efficient data structures used to store and manipulate data in the form of mappings between unique keys and associated values.
Properties of Dictionaries
Mutable: Dictionaries are mutable, meaning you can modify, add, or remove key-value pairs after the dictionary is created.
Unordered: The elements in a dictionary are not stored in any particular order. Unlike sequences like lists or tuples, which are indexed by a range of numbers, dictionaries are indexed by keys.
Key-Value Pairs: Each element in a dictionary consists of a key-value pair. The key is a unique identifier that is used to access the associated value. Keys must be immutable and hashable data types, such as strings, integers, or tuples.
Dynamic: Dictionaries can grow or shrink in size dynamically as key-value pairs are added or removed.
๐dictionary keys must be immutable, types like tuples, strings, integers, etc.This restriction ensures the stability and reliability of dictionary structures.
Operations on Dictionary
Accessing Elements in dictionary
Accessing elements in a dictionary involves retrieving the value associated with a specific key. You can access the value associated with a key in a dictionary using square bracket notation []
.
person = {"name": "Pooja", "age": 30, "city": "Anywhere"}
#Accessing value by key
name = person["name"] # "Pooja"
age = person["age"] # 30
city = person["city"] # "Anywhere"
using theget()
Method: You can use the get()
method to retrieve the value associated with a key. This method returns None
if the key is not found in the dictionary, or a default value can be provided as the second argument.
person = {"name": "Pooja", "age": 30, "city": "Anywhere"}
# Accessing value using get() method
name = person.get("name") # "Pooja"
age = person.get("age") # 30
city = person.get("city") # "Anywhere"
gender = person.get("gender", "Unknown") #Default value if key does not exist
Using the get()
method is safer because it does not raise a KeyError
if the key is not found.
Modifying and Adding Elements
Modifying and adding elements to dictionaries in Python involves updating existing key-value pairs or adding new ones.
Modifying Elements:
To modify an existing key-value pair in a dictionary, simply assign a new value to the corresponding key.
person = {"name": "Pooja", "age": 30, "city": "Anywhere"}
# Modifying the value associated with the "age" key
person["age"] = 35
# Result: {'name': 'Pooja', 'age': 35, 'city': 'Anywhere'}
the value associated with the key 'age'
is modified from 30
to 35
.
Adding Elements:
To add a new key-value pair to a dictionary, assign a value to a new key that doesn't already exist in the dictionary.
person = {"name": "Pooja", "age": 30, "city": "Anywhere"}
#Adding a new key-value pair
person["gender"] = "Female"
#Result: {'name': 'Pooja', 'age': 30, 'city': 'Anywhere', 'gender': 'Female'}
the new key 'gender'
with the value 'Female'
is added to the dictionary person
.
Removing Elements
You can remove key-value pairs from a dictionary using the del
statement or the pop()
method.
#Removing key-value pair using del
del person["city"]
#Removing key-value pair using pop()
gender = person.pop("gender")
Iterate Through a Dictionary
Iterating through a dictionary in Python allows you to access its key-value pairs one by one. There are several ways to iterate through a dictionary:
person = {"name": "Pooja", "age": 30, "city": "Anywhere"}
for key in person.keys():
print(key)
person = {"name": "Pooja", "age": 30, "city": "Anywhere"}
for value in person.values():
print(value)
We can iterate through dictionary keys one by one using a for loop.
Conclusion
Day 10 has been all about dictionaries in Python. We learned that dictionaries are collections of key-value pairs, allowing efficient data storage and retrieval. Here's a quick summary:
Definition: Dictionaries are mutable, unordered data structures.
Creation: They are created using curly braces
{}
and key-value pairs.Access: Elements can be accessed using keys.
Modification: You can modify existing entries or add new ones.
Removal: Entries can be removed using
del
,pop()
, orpopitem()
.Iteration: Dictionaries can be iterated through using
for
loops.
Understanding dictionaries is essential for effective data management in Python.