Summarize the method of deleting multiple dictionary information in the python list

I. Introduction:

In Python, there are several ways to remove multiple dictionary information from a list:

  1. Use list comprehension: Filter out dictionaries that do not need to be deleted through conditional judgment statements to form a new list.
  2. Use  filter() functions: combine lambda expressions and  filter() functions to filter out dictionaries that do not need to be deleted and form a new list.
  3. Use  del keywords: directly delete multiple dictionaries in the list through indexing or slicing operations.

2. How to use:

2.1. Using list comprehension

my_list = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
    {"name": "Charlie", "age": 35},
    {"name": "David", "age": 40}
]

# 删除 age 大于等于 30 的字典
my_list = [item for item in my_list if item["age"] < 30]

print(my_list)

The output is:

[{'name': 'Alice', 'age': 25}]

In the example, we use list comprehension to traverse my_listall the dictionaries in the list, item["age"] < 30filter out the dictionaries that do not need to be deleted through the conditional judgment statement, and finally get a new list.

2.2. Using filter()the function

my_list = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
    {"name": "Charlie", "age": 35},
    {"name": "David", "age": 40}
]

# 删除 age 大于等于 30 的字典
my_list = list(filter(lambda item: item["age"] < 30, my_list))

print(my_list)

The output is:

[{'name': 'Alice', 'age': 25}]

In the example, we use a lambda expression filter()combined with the function to filter out the dictionaries that do not need to be deleted, and convert the result to a list.

2.3. Use delkeywords

my_list = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
    {"name": "Charlie", "age": 35},
    {"name": "David", "age": 40}
]

# 删除索引为 1 和 3 的字典
del my_list[1]
del my_list[3-1]  # 删除第二个元素后,列表长度减 1

print(my_list)

The output is:

[{'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 35}]

In the example, we use delthe keyword to delete the dictionaries indexed 1and respectively through the index operation 2, and print the deleted list. It should be noted that after deleting an element, the length of the list is reduced by 1, so when deleting multiple dictionaries, the index change should be considered.

Guess you like

Origin blog.csdn.net/xun527/article/details/132608314