Python - Extract dictionaries with Empty String value in K key
Last Updated :
04 Apr, 2023
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 :
- Initializes a list of dictionaries called test_list.
- Prints the original list using the print() function.
- Initializes a variable called K with the string value "Gfg".
- Use list comprehension to iterate over each dictionary in test_list and filters the dictionaries with an empty string value for the key K.
- The filtered dictionaries are stored in a new list called res.
- 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))
OutputThe 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))
OutputThe 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))
OutputThe 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))
OutputThe 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))
OutputThe 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
- Import the pandas library using the import keyword and the pandas module.
- 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.
- Print the original list of dictionaries using the print() function and the str() function to convert the list to a string.
- Initialize a variable K to the key that you want to search for empty string values in.
- 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.
- 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.
- 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.
- Store the resulting list of dictionaries in a variable called res.
- 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)
Similar Reads
Python program to extract key-value pairs with substring in a dictionary
Given a dictionary list, extract all the dictionaries which have substring present in particular key. Input : [{"Gfg" : "4", "best" : "1"}, {"Gfg" : "good CS content", "best" : "10"}], K = "Gfg", sub_str = "CS" Output : [{'Gfg': 'good CS content', 'best': '10'}] Explanation : "Gfg" has "CS" as subst
7 min read
Python - Extract dictionaries with values sum greater than K
Given a dictionaries list, extract all the dictionaries whose keys summation exceeds K. Input : test_list = [{"Gfg" : 4, "is" : 8, "best" : 9}, {"Gfg" : 3, "is": 7, "best" : 5}], K = 15 Output : [{'Gfg': 4, 'is': 8, 'best': 9}] Explanation : 4 + 9 + 8 = 21. Greater than K, hence returned. Input : te
8 min read
Python | Extract key-value of dictionary in variables
Sometimes, while working with dictionaries, we can face a problem in which we may have just a singleton dictionary, i.e dictionary with just a single key-value pair, and require to get the pair in separate variables. This kind of problem can come in day-day programming. Let's discuss certain ways in
5 min read
Python - Extract Key's value from Mixed Dictionaries List
Given a list of dictionaries, with each dictionary having different keys, extract value of key K. Input : test_list = [{"Gfg" : 3, "b" : 7}, {"is" : 5, 'a' : 10}, {"Best" : 9, 'c' : 11}], K = 'b' Output : 7 Explanation : Value of b is 7. Input : test_list = [{"Gfg" : 3, "b" : 7}, {"is" : 5, 'a' : 10
7 min read
Python - Dictionary Keys whose Values summation equals K
Given a dictionary and a value K, extract keys whose summation of values equals K. Input : {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks" : 10}, K = 17 Output : ['Best', 'for'] Explanation : 9 + 8 = 17, hence those keys are extracted. Input : {"Gfg" : 3, "is" : 5, "Best" : 9, "for" : 8, "Geeks
9 min read
Python Merge Dictionaries with Same Keys
When working with dictionaries in Python, you should understand that they are mutable, unordered collections of key-value pairs. This flexibility allows us to quickly merge dictionaries, but what happens when two dictionaries have the same key? Python allows us to manage this situation. In this arti
3 min read
Python - Extract ith element of K key's value
Given a dictionary, extract ith element of K key's value list. Input : test_dict = {'Gfg' : [6, 7, 3, 1], 'is' : [9, 1, 4], 'best' : [10, 7, 4]}, K = 'Gfg', i = 1 Output : 7 Explanation : 1st index of 'Gfg''s value is 7.Input : test_dict = {'Gfg' : [6, 7, 3, 1], 'is' : [9, 1, 4], 'best' : [10, 7, 4]
6 min read
Extract Key's Value, if Key Present in List and Dictionary - Python
Given a list, dictionary and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. For example: a = ["Gfg", "is", "Good", "for", "Geeks"], d = {"Gfg": 5, "Best": 6} and K = "Gfg" then the output will be 5 as "Gfg" is present in both the list an
3 min read
Python - Test for Empty Dictionary Value List
Given a dictionary with list as values, check if all lists are empty. Input : {"Gfg" : [], "Best" : []} Output : True Explanation : Both lists have no elements, hence True. Input : {"Gfg" : [], "Best" : [4]} Output : False Explanation : "Best" contains element, Hence False. Method #1 : Using any() +
6 min read
Python - Extract Dictionary Items with Summation Greater than K
Given dictionary with value lists, extract all those items with values summing over K. Input : {"Gfg" : [6, 3, 4], "is" : [8, 10, 12], "Best" : [10, 16, 14], "for" : [7, 4, 3], "geeks" : [1, 2, 3, 4]}, K = 10 Output : {"Gfg" : [6, 3, 4], "is" : [8, 10, 12], "Best" : [10, 16, 14], "for" : [7, 4, 3],
5 min read