Python - Remove Dictionary Key Words

Python - Remove Dictionary Key Words

In this tutorial, we will learn how to remove specific keys (which we'll refer to as "key words") from dictionaries in a list of dictionaries.

Problem Statement:

Given a list of dictionaries and a list of key words, remove the key-value pairs from each dictionary where the key is in the list of key words.

Approach:

  1. Iterate over each dictionary in the list.
  2. For each dictionary, iterate over the list of key words.
  3. If a key word exists in the dictionary, remove the corresponding key-value pair.

Implementation:

def remove_key_words(dict_list, key_words): for d in dict_list: for key in key_words: d.pop(key, None) # Use pop with default to avoid KeyError return dict_list # Test dict_list = [ {"id": 1, "name": "Alice", "age": 25}, {"id": 2, "name": "Bob", "age": 30}, {"id": 3, "name": "Charlie", "address": "123 St"}, {"id": 4, "name": "David", "age": 40} ] key_words = ["name", "address"] print(remove_key_words(dict_list, key_words)) # Output: [{"id": 1, "age": 25}, {"id": 2, "age": 30}, {"id": 3}, {"id": 4, "age": 40}] 

Explanation:

  • The function remove_key_words iterates over each dictionary (d) in the provided list (dict_list).

  • For each dictionary, it further iterates over the list of key words. For each key word, the function attempts to remove the key-value pair with that key from the dictionary using the pop method.

  • The pop method is called with a default value of None to avoid raising a KeyError if the key does not exist in the dictionary.

Summary:

Using nested loops and the dictionary pop method, we can efficiently remove specific key-value pairs from dictionaries in a list. This is a useful approach when we need to sanitize or reduce the data in a list of dictionaries based on certain criteria.


More Tags

future xenomai unit-of-work c#-6.0 uisearchbardisplaycontrol android-virtual-device jradiobutton transpiler datetime-format image-rotation

More Programming Guides

Other Guides

More Programming Examples