Lessons
Python Basics
Python Variables
Operators in Python
Conditional Statements in Python
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Loops in Python
Python Arrays and Functions
Conclusion
Python Add Dictionary
Python Add Items to Dictionaries
In Python, dictionaries are versatile data structures that store data in key-value pairs. One of the key features of dictionaries is the ability to add new items dynamically. This lesson will guide you through the process of adding new entries to a dictionary and updating existing ones.
1. Adding Items to a Dictionary
To add an item to a dictionary, you simply specify a new key and assign a value to it. This operation is straightforward and allows you to expand your dictionary's contents as needed.
Example: Adding a New Item
python
1# Creating a dictionary for a smartphone
2smartphone_specs = {
3 "brand": "Samsung",
4 "model": "Galaxy S21",
5 "year": 2021
6}
7
8# Adding a new item for color
9smartphone_specs["color"] = "Phantom Gray"
10
11print(smartphone_specs) # Output: {'brand': 'Samsung', 'model': 'Galaxy S21', 'year': 2021, 'color': 'Phantom Gray'}
In this example, the new key "color" is added to the smartphone_specs
dictionary, allowing you to store more information about the smartphone.
2. Updating the Dictionary with update()
The update()
method is a powerful way to add or modify multiple items in a dictionary at once. This method takes a dictionary or an iterable of key-value pairs as its argument.
Example: Using update() to Add Items
python
1# Creating a dictionary for a laptop
2laptop_details = {
3 "brand": "Dell",
4 "model": "XPS 13",
5 "year": 2020
6}
7
8# Adding multiple items using update()
9laptop_details.update({"color": "Silver", "RAM": "16GB"})
10
11print(laptop_details) # Output: {'brand': 'Dell', 'model': 'XPS 13', 'year': 2020, 'color': 'Silver', 'RAM': '16GB'}
In this example, we use update()
to add both the "color" and "RAM" entries to the laptop_details
dictionary in one step.
3. Adding Items Using an Iterable
You can also use an iterable object, like a list of tuples, to add multiple key-value pairs at once. This can streamline the process when you have several items to add.
Example: Adding Items from a List of Tuples
python
1# Creating a dictionary for a book
2book_info = {
3 "title": "1984",
4 "author": "George Orwell",
5 "published": 1949
6}
7
8# List of new attributes as tuples
9new_attributes = [("genre", "Dystopian"), ("pages", 328)]
10
11# Adding new attributes using a loop
12for key, value in new_attributes:
13 book_info[key] = value
14
15print(book_info) # Output: {'title': '1984', 'author': 'George Orwell', 'published': 1949, 'genre': 'Dystopian', 'pages': 328}
In this example, we iterate through a list of tuples, adding each new attribute to the book_info
dictionary.