In this article, we will explore how to manipulate dictionaries in Python. Dictionaries are an essential data structure in Python that allows for storing key-value pairs efficiently.
Adding and Updating Elements
We can add new key-value pairs to a dictionary using typical assignment. For example:
d = {'id': 1, 'first_name': 'Scott', 'last_name': 'Tiger', 'amount': 1000.0}
d['commission_pct'] = 10
d['phone_numbers'] = 1234567890
We can update existing key-value pairs in a dictionary by using assignment as well. For instance:
d['amount'] = 1500.0
Accessing Elements
To access elements in a dictionary, we use the setdefault
method. If the key does not exist, it will update the dictionary with the key passed along with a default value. For example:
d.setdefault('amount')
d.setdefault('commission_pct', 0)
Merging Dictionaries
The update
method can be used to merge a list of pairs or another dictionary into the main dictionary. For instance:
d.update({'first_name': 'Donald', 'last_name': 'Duck'})
d.update([('amount', 1000.0), ('commission_pct', 10)])
d.update([('amount', 1500.0), ('commission_pct', 5), ('phone_numbers', 1234567890)])
Removing Elements
You can remove elements from a dictionary using functions like pop
and popitem
.
d.pop('phone_numbers')
d.pop('phone_numbers', 'No such key exists')
d.popitem()
In this article, we have explored various ways to manipulate dictionaries in Python. Practice these concepts and explore further to enhance your Python skills.
Hands-On Tasks
- Create a dictionary with your personal information including name, age, and favorite hobby.
- Update the dictionary with your favorite color as a new key-value pair.
- Remove the ‘age’ key from the dictionary.
Conclusion
In this article, we have learned how to manipulate dictionaries in Python effectively. Practice these concepts through hands-on tasks and engage with the community for further learning journey. Happy coding!