StudyLover
  • Home
  • Study Zone
  • Profiles
  • Contact us
  • Sign in
StudyLover Add Keys
Download
  1. Python
  2. Problem Solving: Lists, Dictionaries, and Function-Based Design
Dictionary Literals : Remove Keys
Problem Solving: Lists, Dictionaries, and Function-Based Design

Add Keys

To add a new key-value pair to a dictionary in Python, you can use the following methods:

1. Direct assignment:

Python

my_dict = {"name": "Alice", "age": 30}

my_dict["city"] = "New York"

print(my_dict)  # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}

2. update() method:

Python

my_dict = {"name": "Alice", "age": 30}

my_dict.update({"city": "New York"})

print(my_dict)  # Output: {'name': 'Alice', 'age': 30, 'city': 'New York'}

3. setdefault() method: This method is useful when you want to add a key-value pair only if the key doesn't already exist:

Python

my_dict = {"name": "Alice", "age": 30}

city = my_dict.setdefault("city", "Unknown")

print(my_dict)  # Output: {'name': 'Alice', 'age': 30, 'city': 'Unknown'}

print(city)  # Output: 'Unknown'

Key points:

  • Keys must be unique within a dictionary.

  • You can add new key-value pairs at any time.

  • The update() method is useful for merging multiple dictionaries.

  • The setdefault() method is helpful for avoiding redundant checks.


Dictionary Literals Remove Keys
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website