Santosh
Santosh

Reputation: 54

Removing key/value pairs in list of dictionary having None Values

inputs : [{'test1': 'test', 'test2': None}]

Exected output : [{'test1': 'test'}]

Upvotes: 0

Views: 491

Answers (4)

Evan Messinger
Evan Messinger

Reputation: 198

Here's a way to process the inputs that results in your expected output. It eliminates key: value pairs from dictionaries where the value is None then eliminates totally empty dictionaries from the list.

data = [{'test1': 'test', 'test2': None}]

output = [entry for entry in [{key: value for key, value in dictionary.items() if value != None} for dictionary in data] if len(entry)>0]
print(output)

EDIT: As per Itamar's comment below, you might want to maintain the original length of the list, for example in the case where you wanted to compare output from a consistent number of functions. Just eliminate the outermost digest:

data = [{'test1': 'test', 'test2': None}]

output = [{key: value for key, value in dictionary.items() if value != None} for dictionary in data]
print(output)

Upvotes: 1

mahesh_1
mahesh_1

Reputation: 158

You can get the desired output using the list comprehension - list comprehension

inputs = [{'test1': 'test', 'test2': None}]

output = [{k: v for k, v in var.items() if v is not None} for var in inputs]
print(output)

Result:

[{'test1': 'test'}]

Upvotes: 1

Santosh
Santosh

Reputation: 54

keep_keys = set()

for d in inputs:
        for key, value in d.items():
                if value is not None:
                        keep_keys.add(key)

remove_keys = set(d) - keep_keys

for d in inputs:
        for k in remove_keys:
                del d[k]

print (inputs)

Upvotes: 0

nowakasd
nowakasd

Reputation: 54

This should do the job

myDict = {key:val for key,val in myDict.items() if val != None}

Upvotes: 0

Related Questions