When I try to do this I get an error saying that the size of the dict has changed during iteration. Is it possible to achieve this without creating another dict?
Thanks!
How do I delete a list of keys from a dictionary?
Is there a way to remove items/keys from a dict in a loop?
How to remove empty dictionary value from list?
Yes the quotes (empty string) are considered values and you would use an if statement. Probably what I would suggest is a list comprehension:
[d for d in mylist if d['name']]
This creates a new list with each dictionary value in there if the value corresponding to the key 'name' is not an empty string. The empty string is a Falsey value in Python, so instead of checking if d['name'] != '' (which is also totally valid) you can just ask if d['name'].
Delete empty keys in a dictionary?
Those aren't empty keys, they're empty values in a list. You can remove them with a list comprehension:
Python 3.6.0b1 (default, Sep 12 2016, 18:11:36) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> foods = ["spam", "ham", "eggs", "bacon", "spam", "", "", ""] >>> [x for x in foods if x] ['spam', 'ham', 'eggs', 'bacon', 'spam']
Also, this seems like a bad use case for CSV. Are you using an existing file with data, or are you building it up itself? If it's the latter, consider JSON or any other non-tabular format, or transpose your table so it looks something like
Alarak true false Artanis true false Lunara false true More on reddit.comVideos
Using dict.pop:
d = {'some': 'data'}
entries_to_remove = ('any', 'iterable')
for k in entries_to_remove:
d.pop(k, None)
Using Dict Comprehensions
final_dict = {key: value for key, value in d.items() if key not in [key1, key2]}
where key1 and key2 are to be removed.
In the example below, keys "b" and "c" are to be removed & it's kept in a keys list.
>>> a
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> keys = ["b", "c"]
>>> print {key: a[key] for key in a if key not in keys}
{'a': 1, 'd': 4}
>>>