- 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 - Change Dictionary Items
Change Dictionary Items
Changing dictionary items in Python refers to modifying the values associated with specific keys within a dictionary. This can involve updating the value of an existing key, adding a new key-value pair, or removing a key-value pair from the dictionary.
Dictionaries are mutable, meaning their contents can be modified after they are created.
Modifying Dictionary Values
Modifying values in a Python dictionary refers to changing the value associated with an existing key. To achieve this, you can directly assign a new value to that key.
Example
In the following example, we are defining a dictionary named "person" with keys 'name', 'age', and 'city' and their corresponding values. Then, we modify the value associated with the key 'age' to 26 −
# Initial dictionary person = {'name': 'Alice', 'age': 25, 'city': 'New York'} # Modifying the value associated with the key 'age' person['age'] = 26 print(person)
It will produce the following output −
{'name': 'Alice', 'age': 26, 'city': 'New York'}
Updating Multiple Dictionary Values
If you need to update multiple values in a dictionary at once, you can use the update() method. This method is used to update a dictionary with elements from another dictionary or an iterable of key-value pairs.
The update() method adds the key-value pairs from the provided dictionary or iterable to the original dictionary, overwriting any existing keys with the new values if they already exist in the original dictionary.
Example
In the example below, we are using the update() method to modify the values associated with the keys 'age' and 'city' in the 'persons' dictionary −
# Initial dictionary person = {'name': 'Alice', 'age': 25, 'city': 'New York'} # Updating multiple values person.update({'age': 26, 'city': 'Los Angeles'}) print(person)
We get the output as shown below −
{'name': 'Alice', 'age': 26, 'city': 'Los Angeles'}
Conditional Dictionary Modification
Conditional modification in a Python dictionary refers to changing the value associated with a key only if a certain condition is met.
You can use an if statement to check whether a certain condition is true before modifying the value associated with a key.
Example
In this example, we conditionally modify the value associated with the key 'age' to '26' if the current value is '25' in the 'persons' dictionary −
# Initial dictionary person = {'name': 'Alice', 'age': 25, 'city': 'New York'} # Conditionally modifying the value associated with 'age' if person['age'] == 25: person['age'] = 26 print(person)
The output obtained is as shown below −
{'name': 'Alice', 'age': 26, 'city': 'New York'}
Modify Dictionary by Adding New Key-Value Pairs
Adding new key-value pairs to a Python dictionary refers to inserting a new key along with its corresponding value into the dictionary.
This process allows you to dynamically expand the data stored in the dictionary by including additional information as needed.
Example: Using Assignment Operator
You can add a new key-value pair to a dictionary by directly assigning a value to a new key as shown below. In the example below, the key 'city' with the value 'New York' is added to the 'person' dictionary −
# Initial dictionary person = {'name': 'Alice', 'age': 25} # Adding a new key-value pair 'city': 'New York' person['city'] = 'New York' print(person)
The result produced is as follows −
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Example: Using the setdefault() Method
You can use the setdefault() method to add a new key-value pair to a dictionary if the key does not already exist.
In this example, the setdefault() method adds the new key 'city' with the value 'New York' to the 'person' dictionary only if the key 'city' does not already exist −
# Initial dictionary person = {'name': 'Alice', 'age': 25} # Adding a new key-value pair 'city': 'New York' person.setdefault('city', 'New York') print(person)
Following is the output of the above code −
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Modify Dictionary by Removing Key-Value Pairs
Removing key-value pairs from a Python dictionary refers to deleting specific keys along with their corresponding values from the dictionary.
This process allows you to selectively remove data from the dictionary based on the keys you want to eliminate.
Example: Using the del Statement
You can use the del statement to remove a specific key-value pair from a dictionary. In this example, the del statement removes the key 'age' along with its associated value from the 'person' dictionary −
# Initial dictionary person = {'name': 'Alice', 'age': 25, 'city': 'New York'} # Removing the key-value pair associated with the key 'age' del person['age'] print(person)
Output of the above code is as shown below −
{'name': 'Alice', 'city': 'New York'}
Example: Using the pop() Method
You can also use the pop() method to remove a specific key-value pair from a dictionary and return the value associated with the removed key.
In here, the pop() method removes the key 'age' along with its associated value from the 'person' dictionary −
# Initial dictionary person = {'name': 'Alice', 'age': 25, 'city': 'New York'} # Removing the key-value pair associated with the key 'age' removed_age = person.pop('age') print(person) print("Removed age:", removed_age)
It will produce the following output −
{'name': 'Alice', 'city': 'New York'} Removed age: 25
Example: Using the popitem() Method
You can use the popitem() method as well to remove the last key-value pair from a dictionary and return it as a tuple.
Now, the popitem() method removes the last key-value pair from the 'person' dictionary and returns it as a tuple −
# Initial dictionary person = {'name': 'Alice', 'age': 25, 'city': 'New York'} # Removing the last key-value pair removed_item = person.popitem() print(person) print("Removed item:", removed_item)
We get the output as shown below −
{'name': 'Alice', 'age': 25} Removed item: ('city', 'New York')