Python – Remove empty value types in dictionaries list
Sometimes, while working with Python dictionaries, we require to remove all the values that are virtually Null, i.e does not hold any meaningful value and are to be removed before processing data, this can be empty string, empty list, dictionary or even 0. This has application in data preprocessing. Lets discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension
This is shorthand to brute way by which this task can be performed. In this we remake the dictionary with only the valid values.
# Python3 code to demonstrate working of # Remove None value types in dictionaries list # Using list comprehension # initializing list test_list = [{ 'gfg' : 4 , 'is' : ' ', ' best ' : []}, {' I ' : {}, ' like ' : 5, ' gfg' : 0 }] # printing original list print ( "The original list is : " + str (test_list)) # Remove None value types in dictionaries list # Using list comprehension res = [ele for ele in ({key: val for key, val in sub.items() if val} for sub in test_list) if ele] # printing result print ( "The filtered list : " + str (res)) |
The original list is : [{'is': '', 'best': [], 'gfg': 4}, {'like': 5, 'gfg': 0, 'I': {}}] The filtered list : [{'gfg': 4}, {'like': 5}]
Method #2 : Using filter() + lambda
+ list comprehension
The combination of above methods can be used to solve this problem. In this, we use filter() + lambda to perform the conditional statement task as in above method to reduce a nesting level.
# Python3 code to demonstrate working of # Remove None value types in dictionaries list # Using filter() + lambda + list comprehension # initializing list test_list = [{ 'gfg' : 4 , 'is' : ' ', ' best ' : []}, {' I ' : {}, ' like ' : 5, ' gfg' : 0 }] # printing original list print ( "The original list is : " + str (test_list)) # Remove None value types in dictionaries list # Using filter() + lambda + list comprehension res = list ( filter ( None , ({key : val for key, val in sub.items() if val} for sub in test_list))) # printing result print ( "The filtered list : " + str (res)) |
The original list is : [{'is': '', 'best': [], 'gfg': 4}, {'like': 5, 'gfg': 0, 'I': {}}] The filtered list : [{'gfg': 4}, {'like': 5}]