How to Delete Dictionaries from a List in Python
This guide explains how to remove specific dictionaries from a list of dictionaries in Python, focusing on filtering based on key-value pairs. We'll cover using list comprehensions, the filter()
function, and for
loops. We'll also distinguish between loading JSON from a file and working with existing Python lists of dictionaries.
Deleting Dictionaries Based on a Condition (List Comprehension - Recommended)
List comprehensions provide the most concise and Pythonic way to create a new list containing only the dictionaries that meet a specific condition. This is generally the preferred approach.
list_of_dictionaries = [
{'id': 1, 'name': 'alice'},
{'id': 2, 'name': 'anna'},
{'id': 3, 'name': 'carl'},
]
filtered_list = [
d for d in list_of_dictionaries if d['id'] != 2 # Keep if id is NOT 2
]
print(filtered_list)
# Output: [{'id': 1, 'name': 'alice'}, {'id': 3, 'name': 'carl'}]
- This code iterates through the
list_of_dictionaries
. - For each dictionary
d
the code checks if theid
is not equal to2
. - The result is a new list containing the filtered dictionaries.
You can easily adapt this to other conditions. For example, to remove dictionaries where the 'name' is 'anna':
filtered_list = [d for d in list_of_dictionaries if d['name'] != 'anna']
print(filtered_list) # Output: [{'id': 1, 'name': 'alice'}, {'id': 3, 'name': 'carl'}]
Deleting Dictionaries with a for
Loop (and pop()
)
You can modify the list in-place using a for
loop and pop()
, but this is more error-prone and less efficient than a list comprehension. You must iterate in reverse order when modifying a list in place.
list_of_dictionaries = [
{'id': 1, 'name': 'alice'},
{'id': 2, 'name': 'anna'},
{'id': 3, 'name': 'carl'},
]
# Iterate in REVERSE order when modifying in place.
for i in range(len(list_of_dictionaries) - 1, -1, -1):
if list_of_dictionaries[i]['id'] == 2:
list_of_dictionaries.pop(i)
print(list_of_dictionaries)
# Output: [{'id': 1, 'name': 'alice'}, {'id': 3, 'name': 'carl'}]
range(len(list_of_dictionaries) - 1, -1, -1)
: This creates a sequence of indices in reverse order, from the last element's index down to 0. This is crucial. If you iterate forward and remove elements, you'll skip over elements and potentially getIndexError
exceptions.- The
break
statement can be used to stop the loop if you only want to delete one element.
Deleting Dictionaries with filter()
The filter()
function provides another way to create a new list, filtering out unwanted dictionaries:
list_of_dictionaries = [
{'id': 1, 'name': 'alice'},
{'id': 2, 'name': 'anna'},
{'id': 3, 'name': 'carl'},
]
new_list = list(filter(lambda x: x['name'] != 'anna', list_of_dictionaries))
print(new_list)
# Output: [{'id': 1, 'name': 'alice'}, {'id': 3, 'name': 'carl'}]
filter()
returns an iterator, and the result is cast to a list usinglist()
.- This is less readable than the list comprehension for simple filtering, but can be useful for more complex filter logic.
Working with JSON Files vs. In-Memory Lists
It's important to distinguish between working with JSON files and working with Python lists of dictionaries that happen to contain JSON-like data.
json.load()
vs. json.loads()
-
json.load(file_object)
: Reads a JSON file and converts it into a Python object (usually a list or dictionary). Use this when you're loading data from a file.import json
with open('example.json', 'r', encoding='utf-8') as f:
my_list = json.load(f) # Load from a FILE -
json.loads(json_string)
: Parses a JSON string into a Python object. Use this when you already have a JSON string in memory.import json
my_json = '[{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]'
my_list = json.loads(my_json) # Load from a STRING
Writing to a New File
To write the updated data into a JSON file, use the json.dump
function.
import json
file_name = 'example.json'
with open(file_name, 'r', encoding='utf-8') as f:
my_list = json.load(f)
new_list = [d for d in my_list if d['id'] != 2] # remove dicts where id is 2
new_file_name = 'new-file.json'
with open(new_file_name, 'w', encoding='utf-8') as f:
json.dump(new_list, f, indent=2) # Write to a new file, with indent