Dictionary Key-Value Operations: Tips for Adding, Removing, Modifying, and Querying in Python Dictionaries

A dictionary is a very useful data structure in Python, used to store key-value pairs. Unlike lists, dictionary keys must be immutable types (such as strings, numbers) and unique, while values can be of any type. Through “add, delete, modify, and query” operations, we can flexibly manage the data in the dictionary.

I. Basic Definition of Dictionary

Dictionaries are created using {}, with the format {key1: value1, key2: value2, ...}. For example:

student = {
    'name': '小明',
    'age': 18,
    'gender': '男'
}
  • Key: Unique and immutable (e.g., strings, numbers), used to locate values.
  • Value: Can be of any type (numbers, strings, lists, dictionaries, etc.).

II. Dictionary “Add”: Adding Key-Value Pairs

To add a new key-value pair to a dictionary, simply use the assignment operation (if the key does not exist, it will be added; if the key already exists, its value will be modified).

1. Direct Assignment (Add/Modify)

student = {'name': '小明', 'age': 18}

# Add a new key-value pair (when the key does not exist)
student['gender'] = '男'
print(student)  # Output: {'name': '小明', 'age': 18, 'gender': '男'}

# Modify the value of an existing key (when the key exists)
student['age'] = 19
print(student)  # Output: {'name': '小明', 'age': 19, 'gender': '男'}

III. Dictionary “Delete”: Removing Key-Value Pairs

Delete operations are used to remove certain key-value pairs from a dictionary. Common methods include del, pop(), popitem(), and clear().

1. del Statement: Delete a Specified Key

student = {'name': '小明', 'age': 18, 'gender': '男'}

del student['age']  # Delete the key 'age'
print(student)  # Output: {'name': '小明', 'gender': '男'}
  • Note: If the key does not exist, a KeyError will be raised.

2. pop() Method: Delete and Return the Value

pop(key, default): If the key exists, delete and return its value; if the key does not exist, return default (default is None).

student = {'name': '小明', 'age': 18}

# Delete 'name' and return its value
name = student.pop('name')
print(name)  # Output: 小明
print(student)  # Output: {'age': 18}

# Specify a default value if the key does not exist
score = student.pop('score', '未知')
print(score)  # Output: 未知

3. popitem() Method: Delete the Last Key-Value Pair

In Python 3.7+, popitem() deletes and returns the last inserted key-value pair (randomly deleted in previous versions).

student = {'name': '小明', 'age': 18, 'gender': '男'}

item = student.popitem()  # Delete the last key-value pair
print(item)  # Output: ('gender', '男')
print(student)  # Output: {'name': '小明', 'age': 18}

4. clear() Method: Clear the Dictionary

student = {'name': '小明', 'age': 18}
student.clear()  # Clear the dictionary
print(student)  # Output: {}

IV. Dictionary “Modify”: Modify the Value of an Existing Key

If the key already exists, directly use the assignment operation to overwrite the old value:

student = {'name': '小明', 'age': 18}

student['age'] = 19  # Modify the value of 'age'
print(student)  # Output: {'name': '小明', 'age': 19}
  • Essence: This is consistent with the “add” operation (the key is modified if it exists, or added if it does not exist).

V. Dictionary “Query”: Get the Value Corresponding to a Key

There are multiple ways to query values. It is recommended to use get() first to avoid errors.

1. Direct Key Access (Error-Prone)

student = {'name': '小明', 'age': 18}

print(student['name'])  # Output: 小明
# print(student['score'])  # Error: KeyError: 'score' (key does not exist)

2. get() Method (Safe Query)

get(key, default): Returns the value if the key exists, otherwise returns default (default is None).

student = {'name': '小明', 'age': 18}

# Returns the value when the key exists
print(student.get('name'))  # Output: 小明

# Returns the default value when the key does not exist
score = student.get('score', '0分')
print(score)  # Output: 0分

3. Batch Query Keys/Values/Key-Value Pairs

  • keys(): Get all keys (returns a view object, which can be converted to a list).
  • values(): Get all values (returns a view object).
  • items(): Get all key-value pairs (returns a tuple view).
student = {'name': '小明', 'age': 18, 'gender': '男'}

print(student.keys())   # Output: dict_keys(['name', 'age', 'gender'])
print(student.values()) # Output: dict_values(['小明', 18, '男'])
print(student.items())  # Output: dict_items([('name', '小明'), ('age', 18), ('gender', '男')])

# Convert to a list for easy iteration
print(list(student.keys()))  # Output: ['name', 'age', 'gender']

VI. Notes

  1. Keys Must Be Unique and Immutable: Repeated keys will be overwritten; lists and sets cannot be used as keys.
   my_dict = {[1,2]: 'test'}  # Error: List cannot be used as a key
  1. Avoid Errors Caused by Non-Existent Keys: Prefer get() over direct key access for querying.
  2. Unified Nature of Modification and Addition: dict[key] = value can both modify existing keys and add new ones, depending on whether the key exists.

Through the above “add, delete, modify, and query” operations, you can flexibly manage the data in the dictionary. In daily use, it is recommended to use get() for querying and pop() for deletion, and pay attention to the uniqueness and immutability of keys.

Xiaoye