Efficient Way to Remove Keys with Empty Strings from a Dict

Efficient way to remove keys with empty strings from a dict

Python 2.X

dict((k, v) for k, v in metadata.iteritems() if v)

Python 2.7 - 3.X

{k: v for k, v in metadata.items() if v}

Note that all of your keys have values. It's just that some of those values are the empty string. There's no such thing as a key in a dict without a value; if it didn't have a value, it wouldn't be in the dict.

What is efficient way of removing empty values from dict inside list?

Try this:

list1 = [{'l1k1': 'l1v1', 'l1k2': 'l1v2'}, {'l2k1': 'l2v1', 'l2k2': ''}]
list2 = [{ k: v for k, v in d.items() if v and v.strip() } for d in list1]

Notice that the correct check to do here is v and v.strip(), that ensures that the string is not None and is not all spaces. It works as expected:

list2
=> [{'l1k1': 'l1v1', 'l1k2': 'l1v2'}, {'l2k1': 'l2v1'}]

It's efficient because it uses list comprehensions and dictionary comprehensions, which are faster than doing explicit loops. Also, it's quite compact and idiomatic :)

Delete keys of a dictionary whose values are empty lists

What about:

new_d = dict((k,v) for k,v in d.items() if v)

And if you wish to overwrite d just change new_d to d.

There is some risk that might gives the wrong results:

if v when v = [] will evaluate to Falsly, same as 0 so it might remove wrong key. In my answer I didn't address that. One can refer to the following link to understand better: What is Truthy and Falsy? How is it different from True and False?

Remove empty value from lists which are in a dict

Nested comprehensions will let you make a new dict:

original_dict = {"abc": ["","red","green","blue"], "def":["amber","silver","","gold","black","",""]}
output_dict = {k: [x for x in v if x] for k, v in original_dict.items()}

If you want to modify the original dict and its lists in place (so aliases see all changes, whether they alias the dict or the contained lists), you can avoid touching the keys and just replace the contents of each list with the pruned version, like so:

for v in original_dict.values():
v[:] = [x for x in v if x] # Or v[:] = filter(None, v) if you prefer

The [:] in there is what makes even aliases of the lists get changed. If you didn't want to change them in-place, you'd need the keys (to enable reassignment) and you'd instead do:

for k, v in original_dict.items():
original_dict[k] = [x for x in v if x]

Most efficient way to remove a string pattern of several keys based on a list of patterns and removing duplicate keys

how about a own function to clean keys?

pattern_list = ['_PATTERN1','_PATTERN2']
def clean_key(key):
for pattern in pattern_list:
key = key.replace(pattern, "")
return key
{clean_key(k) : v for k, v in x.items()}

How to remove empty or None fields in deeply nested dictionary of unknown depth?

You can use recursion with a dictionary comprehension:

d = {'1': {'1_1': 'a real value', '1_2': ''}, '2': None, '3': {'3_1': {'3_2': None}}}
def get_d(d):
return {a:c for a, b in d.items() if (c:=(b if not isinstance(b, dict) else get_d(b)))}

print(get_d(d))

Output:

{'1': {'1_1': 'a real value'}}

Note: this solution uses Python's assignment expressions (:=) available in versions >= 3.8. For a solution that does not use this paradigm, please see @Anonymous's answer.

How to remove empty string in a list within a dictionary?

dictionary = {}
dictionary['a']= ('name',['','p','q','',''])
for key in dictionary.keys():
x,y = dictionary[key]
print(x,y)
dictionary[key] =(x, [s for s in y if len(s)!=0])



Related Topics



Leave a reply



Submit