Reputation: 5402
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': '[email protected]', ...
If you delete the key, will it delete its respective value? How can I get rid of empty keys and values?
Upvotes: 2
Views: 4314
Reputation: 18047
Try this,
post_dict = {'': '', 'item_data[username]': ['johndoe'], 'item_data[email]': ['[email protected]'], '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': '[email protected]'}
Previous answer: Delete those items from a dict whose key or value is empty.
d = {'': '', 'username': 'johndoe', 'email': '[email protected]'}
for k, v in d.items():
if not any([k, v]):
del d[k]
print(d)
{'username': 'johndoe', 'email': '[email protected]'}
Upvotes: 0
Reputation: 1468
Maybe you can do what you want using one of these:
dict_1 = {'': '', 'username': 'johndoe', 'email':'', }
dict_2 = dict(x for x in dict_1.iteritems() if any(x))
print dict_2 # {'username': 'johndoe', 'email': ''}
dict_3 = dict(x for x in dict_1.iteritems() if all(x))
print dict_3 # {'username': 'johndoe'}
Upvotes: 2
Reputation: 18722
Try this:
new_item_data={k:item_data[k] for k in item_data if item_data[k]}
Any keys that do not have values will be removed.
Upvotes: 3
Reputation: 61
for key, value in post_dict.items():
In your code you are iterating on post_dict
.
However, in the line del post_dict[key]
you are modifying the iterator, so it will provide an inconsistent view of the dictionary to for
. It is not good to add or delete keys to the dictionary that you are iterating on.
This may give the result you wanted
post_dict = dict(request.POST)
item_data = {}
for key, value in post_dict.items():
if value == "":
continue
if key == "":
continue
field = key.split('[')[1].replace(']', '')
item_data[field] = ''.join(value)
print(item_data)
Upvotes: 2