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 list
s in place (so aliases see all changes, whether they alias the dict
or the contained list
s), 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 list
s 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
Can Pandas Plot a Histogram of Dates
Crawling with an Authenticated Session in Scrapy
Sampling Uniformly Distributed Random Points Inside a Spherical Volume
How to Correctly Parse Utf-8 Encoded HTML to Unicode Strings with Beautifulsoup
Define a Method Outside of Class Definition
How to Enable Pan and Zoom in a Qgraphicsview
Changing User Agent in Python 3 for Urrlib.Request.Urlopen
Curses Alternative for Windows
Extract Day of Year and Julian Day from a String Date
How to Use Python Numpy.Savetxt to Write Strings and Float Number to an Ascii File
How to Add a Custom Loglevel to Python's Logging Facility
When to Close Cursors Using MySQLdb
Appending List But Error 'Nonetype' Object Has No Attribute 'Append'
How to Do Row-To-Column Transposition of Data in CSV Table
How to Quickly Estimate the Distance Between Two (Latitude, Longitude) Points
How to Include a Python Package with Hadoop Streaming Job