Modelesq Modelesq - 1 year ago 107
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)


What the print item_data looks like:

{'': '', 'username': 'johndoe', 'email': '', ...

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

Answer Source

Try this,

post_dict = {'': '', 'item_data[username]': ['johndoe'], 'item_data[email]': [''], 'item_data[campus]': ['madison']}
item_data = {}

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

    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

# Output
{'username': 'johndoe', 'campus': 'madison', 'email': ''}

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

d = {'': '', 'username': 'johndoe', 'email': ''}

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

{'username': 'johndoe', 'email': ''}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download