How to add items to a dictionary in Python?
Table of Contents
Introduction
Adding items to a dictionary in Python involves inserting new key-value pairs or updating existing ones. Dictionaries are mutable, so you can dynamically modify them by adding or updating items as needed.
Methods to Add Items
Using Square Brackets []
You can add a new item to a dictionary by assigning a value to a new key using square brackets. If the key already exists, its value will be updated; if it does not exist, a new key-value pair will be created.
Example:
Using the update() Method
The update() method allows you to add multiple key-value pairs to a dictionary at once. You can pass another dictionary or an iterable of key-value pairs to this method.
Example:
Using Dictionary Comprehension
Dictionary comprehension is a concise way to create and add items to a dictionary based on existing data. It is particularly useful for transforming or filtering data.
Example:
Using the setdefault() Method
The setdefault() method adds a key-value pair to the dictionary if the key does not already exist. If the key exists, it returns the value associated with it without updating.
Example:
Practical Examples
Example 1: Adding User Information
Example 2: Merging Dictionaries
Conclusion
Adding items to a Python dictionary can be done using various methods such as square brackets, the update() method, dictionary comprehension, and setdefault(). Each method has its own use cases, allowing for flexible and efficient dictionary management.