Modelesq Modelesq - 5 months ago 9
Python Question

How to remove dict keys if value is empty

In my form post request I'm grabbing all form info, but it seems as though there are some empty keys and values. I'd like to remove all instances of empty keys and values. This what I have so far, and it's obviously not working.

post_dict = dict(request.POST)
item_data = {}

for key, value in post_dict.items():
if value is None:
del post_dict[key]
field = key.split('[')[1].replace(']', '')
item_data[field] = ''.join(value)

print(item_data)


What the print item_data looks like:

{'': '', 'username': 'johndoe', 'email': 'johndoe@gmail.com', ...


If you delete the key, will it delete its respective value? How can I get rid of empty keys and values?

Answer

Try this,

post_dict = {'': '', 'item_data[username]': ['johndoe'], 'item_data[email]': ['johndoe@gmail.com'], 'item_data[campus]': ['madison']}
item_data = {}

for key, value in post_dict.items():
    strlist = key.split('[')
    if len(strlist) == 1:
        continue

    new_key = strlist[1].replace(']', '')
    new_value = ''.join(value)

    # add to the dict if both new_key and new_value are non-empty
    if all([new_key, new_value]):
        item_data[new_key] = new_value

print(item_data)
# Output
{'username': 'johndoe', 'campus': 'madison', 'email': 'johndoe@gmail.com'}

Previous answer: Delete those items from a dict whose key or value is empty.

d = {'': '', 'username': 'johndoe', 'email': 'johndoe@gmail.com'}

for k, v in d.items():
    if not any([k, v]):
        del d[k]

print(d)
{'username': 'johndoe', 'email': 'johndoe@gmail.com'}
Comments