Open In App

Python – Extract dictionaries with Empty String value in K key

Improve
Improve
Like Article
Like
Save
Share
Report

Given a List of dictionaries, extract all the dictionaries which have empty strings as values of a particular key.

Input : test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"}, 
                    {"Gfg" : "9", "is" : "CS", "best" : "10"}], K = "Gfg" 
Output : [] 
Explanation : No "Gfg" key is empty. 

Input : test_list = [{"Gfg" : "", "is" : "good", "best" : "1"}, 
                    {"Gfg" : "9", "is" : "CS", "best" : "10"}], K = "Gfg" 
Output : [{"Gfg" : "", "is" : "good", "best" : "1"}] 
Explanation : Dictionary with empty "Gfg" extracted.

Method #1:  Using list comprehension

This is one of the ways in which this task can be performed. In this, we run a loop through all dictionaries and check for key’s empty string value. All this was compiled in list comprehension rather than loop.

Step-by-step approach :

  1. Initializes a list of dictionaries called test_list.
  2. Prints the original list using the print() function.
  3. Initializes a variable called K with the string value “Gfg”.
  4. Use list comprehension to iterate over each dictionary in test_list and filters the dictionaries with an empty string value for the key K.
  5. The filtered dictionaries are stored in a new list called res.
  6. Prints the extracted dictionaries using the print() function.

Python3




# Python3 code to demonstrate working of
# Extract dictionaries with Empty String value in K key
# Using list comprehension
 
# initializing lists
test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"},
             {"Gfg" : "", "is" : "better", "best" : "8"},
             {"Gfg" : "9", "is" : "CS", "best" : "10"}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K key
K = "Gfg"
 
# using list comprehension to fetch empty string key's dictionaries
res = [sub for sub in test_list if sub[K] == '']
     
# printing result
print("The extracted dictionaries : " + str(res))


Output

The original list : [{'Gfg': '4', 'is': 'good', 'best': '1'}, {'Gfg': '', 'is': 'better', 'best': '8'}, {'Gfg': '9', 'is': 'CS', 'best': '10'}]
The extracted dictionaries : [{'Gfg': '', 'is': 'better', 'best': '8'}]

Time Complexity: O(n), where n is the number of dictionaries in the list.

Auxiliary Space: O(n), where n is the number of dictionaries in the list.

Method #2 :  Using filter() + lambda

This is yet another way in which this task can be performed. In this, we extract all the empty values key’s dictionaries using filter() and functionality and iteration by lambda.

Python3




# Python3 code to demonstrate working of
# Extract dictionaries with Empty String value in K key
# Using filter() + lambda
 
# initializing lists
test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"},
             {"Gfg" : "", "is" : "better", "best" : "8"},
             {"Gfg" : "9", "is" : "CS", "best" : "10"}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K key
K = "Gfg"
 
# filter() used to iteration
# lambda for functionality
res = list(filter(lambda sub: sub[K] == '', test_list))
     
# printing result
print("The extracted dictionaries : " + str(res))


Output

The original list : [{'Gfg': '4', 'is': 'good', 'best': '1'}, {'Gfg': '', 'is': 'better', 'best': '8'}, {'Gfg': '9', 'is': 'CS', 'best': '10'}]
The extracted dictionaries : [{'Gfg': '', 'is': 'better', 'best': '8'}]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3 : Using len() and keys() methods

Python3




# Python3 code to demonstrate working of
# Extract dictionaries with Empty String value in K key
 
# initializing lists
test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"},
            {"Gfg" : "", "is" : "better", "best" : "8"},
            {"Gfg" : "9", "is" : "CS", "best" : "10"}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K key
K = "Gfg"
res = []
for i in test_list:
    if K in i.keys() and len(i[K])==0 :
        res.append(i)
# printing result
print("The extracted dictionaries : " + str(res))


Output

The original list : [{'Gfg': '4', 'is': 'good', 'best': '1'}, {'Gfg': '', 'is': 'better', 'best': '8'}, {'Gfg': '9', 'is': 'CS', 'best': '10'}]
The extracted dictionaries : [{'Gfg': '', 'is': 'better', 'best': '8'}]

Time complexity of this code is O(n), where n is the length of the input list test_list, because we are iterating over each dictionary in the list once.

Auxiliary space used by this code is also O(n), because we are creating a list res to store the dictionaries that have an empty string as value for the key K. 

Method 4: Using for loop and if statement

The loop iterates through each dictionary in test_list, and the if statement checks if the value associated with the key K is an empty string. If it is, the dictionary is appended to the res list. Finally, the res list is printed.

Python3




# Python3 code to demonstrate working of
# Extract dictionaries with Empty String value in K key
# Using for loop and if statement
 
# initializing lists
test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"},
             {"Gfg" : "", "is" : "better", "best" : "8"},
             {"Gfg" : "9", "is" : "CS", "best" : "10"}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K key
K = "Gfg"
 
# using for loop and if statement to fetch empty string key's dictionaries
res = []
for sub in test_list:
    if sub[K] == '':
        res.append(sub)
     
# printing result
print("The extracted dictionaries : " + str(res))


Output

The original list : [{'Gfg': '4', 'is': 'good', 'best': '1'}, {'Gfg': '', 'is': 'better', 'best': '8'}, {'Gfg': '9', 'is': 'CS', 'best': '10'}]
The extracted dictionaries : [{'Gfg': '', 'is': 'better', 'best': '8'}]

Time Complexity: O(n), where n is the number of dictionaries in test_list. This is because the loop iterates through each dictionary in test_list exactly once.
Auxiliary Space: O(k), where k is the number of dictionaries in test_list that have an empty string value associated with the key K. This is because the res list will have at most k dictionaries appended to it.

Method 5: Using map() + lambda

In this approach, the lambda function inside the map() function returns the dictionary if the value of the K key is an empty string, and None otherwise. The filter() function then removes all the None values from the resulting list.

Python3




test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"},
             {"Gfg" : "", "is" : "better", "best" : "8"},
             {"Gfg" : "9", "is" : "CS", "best" : "10"}]
 
K = "Gfg"
 
res = list(filter(lambda x: x != None, map(lambda x: x if x[K] == '' else None, test_list)))
 
print("The extracted dictionaries : " + str(res))


Output

The extracted dictionaries : [{'Gfg': '', 'is': 'better', 'best': '8'}]

Time Complexity: O(n), where n is the number of dictionaries in the input list.

Auxiliary Space: O(k), where k is the number of dictionaries in the output list. 

Method 6: Using the pandas library

  1. Import the pandas library using the import keyword and the pandas module.
  2. Initialize a list of dictionaries called test_list. Each dictionary represents a row of data, with keys representing column names and values representing the data in each column.
  3. Print the original list of dictionaries using the print() function and the str() function to convert the list to a string.
  4. Initialize a variable K to the key that you want to search for empty string values in.
  5. Create a pandas dataframe from the list of dictionaries using the pd.DataFrame() method. This will create a table with columns corresponding to the keys of the dictionaries and rows corresponding to the dictionaries in the list.
  6. Select the dictionaries with an empty string value in the K key using boolean indexing. This can be done by creating a boolean mask with the condition df[K] == ” and passing it as an index to the dataframe.
  7. Convert the resulting dataframe to a list of dictionaries using the to_dict() method with the argument ‘records’. This will create a list of dictionaries where each dictionary represents a row of data.
  8. Store the resulting list of dictionaries in a variable called res.
  9. Print the extracted dictionaries using the print() function and the str() function to convert the list to a string.

Python3




# importing the pandas library
import pandas as pd
 
# initializing lists
test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"},
             {"Gfg" : "", "is" : "better", "best" : "8"},
             {"Gfg" : "9", "is" : "CS", "best" : "10"}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K key
K = "Gfg"
 
# creating a pandas dataframe from the list of dictionaries
df = pd.DataFrame(test_list)
 
# selecting the dictionaries with an empty string value in the K key
res = df[df[K] == ''].to_dict('records')
 
# printing the result
print("The extracted dictionaries : " + str(res))


OUTPUT:

The original list : [{'Gfg': '4', 'is': 'good', 'best': '1'}, {'Gfg': '', 'is': 'better', 'best': '8'}, {'Gfg': '9', 'is': 'CS', 'best': '10'}]
The extracted dictionaries : [{'Gfg': '', 'is': 'better', 'best': '8'}]

Time complexity: O(n), where n is the number of dictionaries in the list.
Auxiliary space: O(n), where n is the number of dictionaries in the list (due to the creation of the pandas dataframe)



Last Updated : 04 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads