- Python Basics
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Comparison Operators
- Python - Assignment Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Operator Precedence
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python Control Statements
- Python - Control Flow
- Python - Decision Making
- Python - If Statement
- Python - If else
- Python - Nested If
- Python - Match-Case Statement
- Python - Loops
- Python - for Loops
- Python - for-else Loops
- Python - While Loops
- Python - break Statement
- Python - continue Statement
- Python - pass Statement
- Python - Nested Loops
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Python - OS Path Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Classes & Objects
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Libraries
- NumPy Tutorial
- Pandas Tutorial
- SciPy Tutorial
- Matplotlib Tutorial
- Django Tutorial
- OpenCV Tutorial
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Useful Resources
- Python Compiler
- NumPy Compiler
- Matplotlib Compiler
- SciPy Compiler
- Python - Questions & Answers
- Python - Online Quiz
- Python - Programming Examples
- Python - Quick Guide
- Python - Useful Resources
- Python - Discussion
Python - Add Dictionary Items
Add Dictionary Items
Adding dictionary items in Python refers to inserting new key-value pairs into an existing dictionary. Dictionaries are mutable data structures that store collections of key-value pairs, where each key is associated with a corresponding value.
Adding items to a dictionary allows you to dynamically update and expand its contents as needed during program execution.
We can add dictionary items in Python using various ways such as −
- Using square brackets
- Using the update() method
- Using a comprehension
- Using unpacking
- Using the Union Operator
- Using the |= Operator
- Using setdefault() method
- Using collections.defaultdict() method
Add Dictionary Item Using Square Brackets
The square brackets [] in Python is used to access elements in sequences like lists and strings through indexing and slicing operations. Additionally, when working with dictionaries, square brackets are used to specify keys for accessing or modifying associated values.
You can add items to a dictionary by specifying the key within square brackets and assigning a value to it. If the key is already present in the dictionary object, its value will be updated to val. If the key is not present in the dictionary, a new key-value pair will be added.
Example
In this example, we are creating a dictionary named "marks" with keys representing names and their corresponding integer values. Then, we add a new key-value pair 'Kavta': 58 to the dictionary using square bracket notation −
marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49} print ("Initial dictionary: ", marks) marks['Kavya'] = 58 print ("Dictionary after new addition: ", marks)
It will produce the following output −
Initial dictionary: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49} Dictionary after new addition: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49, 'Kavya': 58}
Add Dictionary Item Using the update() Method
The update() method in Python dictionaries is used to merge the contents of another dictionary or an iterable of key-value pairs into the current dictionary. It adds or updates key-value pairs, ensuring that existing keys are updated with new values and new keys are added to the dictionary.
You can add multiple items to a dictionary using the update() method by passing another dictionary or an iterable of key-value pairs.
Example
In the following example, we use the update() method to add multiple new key-value pairs 'Kavya': 58 and 'Mohan': 98 to the dictionary 'marks' −
marks = {"Savita":67, "Imtiaz":88} print ("Initial dictionary: ", marks) marks.update({'Kavya': 58, 'Mohan': 98}) print ("Dictionary after new addition: ", marks)
We get the output as shown below −
Initial dictionary: {'Savita': 67, 'Imtiaz': 88} Dictionary after new addition: {'Savita': 67, 'Imtiaz': 88, 'Kavya': 58, 'Mohan': 98}
Add Dictionary Item Using Unpacking
Unpacking in Python refers to extracting individual elements from a collection, such as a list, tuple, or dictionary, and assigning them to variables in a single statement. This can be done using the * operator for iterables like lists and tuples, and the ** operator for dictionaries.
We can add dictionary items using unpacking by combining two or more dictionaries with the ** unpacking operator.
Example
In the example below, we are initializing two dictionaries named "marks" and "marks1", both containing names and their corresponding integer values. Then, we create a new dictionary "newmarks" by merging "marks" and "marks1" using dictionary unpacking −
marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49} print ("marks dictionary before update: \n", marks) marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89} newmarks = {**marks, **marks1} print ("marks dictionary after update: \n", newmarks)
Following is the output of the above code −
marks dictionary before update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49} marks dictionary after update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}
Add Dictionary Item Using the Union Operator (|)
The union operator in Python, represented by the | symbol, is used to combine the elements of two sets into a new set that contains all the unique elements from both sets. It can also be used with dictionaries in Python 3.9 and later to merge the contents of two dictionaries.
We can add dictionary items using the union operator by merging two dictionaries into a new dictionary, which includes all key-value pairs from both dictionaries.
Example
In this example, we are using the | operator to combine the dictionaries "marks" and "marks1" with "marks1" values taking precedence in case of duplicate keys −
marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49} print ("marks dictionary before update: \n", marks) marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89} newmarks = marks | marks1 print ("marks dictionary after update: \n", newmarks)
Output of the above code is as shown below −
marks dictionary before update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49} marks dictionary after update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}
Add Dictionary Item Using the "|=" Operator
The |= operator in Python is an in-place union operator for sets and dictionaries. It updates the set or dictionary on the left-hand side with elements from the set or dictionary on the right-hand side.
We can add dictionary items using the |= operator by updating an existing dictionary with key-value pairs from another dictionary. If there are overlapping keys, the values from the right-hand dictionary will overwrite those in the left-hand dictionary.
Example
In the following example, we use the |= operator to update "marks" with the key-value pairs from "marks1", with values from "marks1" taking precedence in case of duplicate keys −
marks = {"Savita":67, "Imtiaz":88, "Laxman":91, "David":49} print ("marks dictionary before update: \n", marks) marks1 = {"Sharad": 51, "Mushtaq": 61, "Laxman": 89} marks |= marks1 print ("marks dictionary after update: \n", marks)
The output produced is as shown below −
marks dictionary before update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 91, 'David': 49} marks dictionary after update: {'Savita': 67, 'Imtiaz': 88, 'Laxman': 89, 'David': 49, 'Sharad': 51, 'Mushtaq': 61}
Add Dictionary Item Using the setdefault() Method
The setdefault() method in Python is used to get the value of a specified key in a dictionary. If the key does not exist, it inserts the key with a specified default value.
We can add dictionary items using the setdefault() method by specifying a key and a default value.
Example
In this example, we use the setdefault() to add the key-value pair "major": "Computer Science" to the "student" dictionary −
# Initial dictionary student = {"name": "Alice", "age": 21} # Adding a new key-value pair major = student.setdefault("major", "Computer Science") print(student)
Since the key "major" does not exist, it is added with the specified default value as shown in the output below −
{'name': 'Alice', 'age': 21, 'major': 'Computer Science'}
Add Dictionary Item Using the collections.defaultdict() Method
The collections.defaultdict() method in Python is a subclass of the built-in "dict" class that creates dictionaries with default values for keys that have not been set yet. It is part of the collections module in Python's standard library.
We can add dictionary items using the collections.defaultdict() method by specifying a default factory, which determines the default value for keys that have not been set yet. When accessing a missing key for the first time, the default factory is called to create a default value, and this value is inserted into the dictionary.
Example
In this example, we are initializing instances of defaultdict with different default factories: int to initialize missing keys with 0, list to initialize missing keys with an empty list, and a custom function default_value to initialize missing keys with the return value of the function −
from collections import defaultdict # Using int as the default factory to initialize missing keys with 0 d = defaultdict(int) # Incrementing the value for key 'a' d["a"] += 1 print(d) # Using list as the default factory to initialize missing keys with an empty list d = defaultdict(list) # Appending to the list for key 'b' d["b"].append(1) print(d) # Using a custom function as the default factory def default_value(): return "N/A" d = defaultdict(default_value) print(d["c"])
The output obtained is as follows −
defaultdict(<class 'int'>, {'a': 1}) defaultdict(<class 'list'>, {'b': [1]}) N/A