How about a dict comprehension:
filtered_dict = {k: v for k, v in d.iteritems() if filter_string in k}
One you see it, it should be self-explanatory, as it reads like English pretty well.
This syntax requires Python 2.7 or greater.
In Python 3, there is only dict.items(), not iteritems() so you would use:
filtered_dict = {k: v for k, v in d.items() if filter_string in k}
Answer from Jonathon Reinhart on Stack OverflowHow about a dict comprehension:
filtered_dict = {k: v for k, v in d.iteritems() if filter_string in k}
One you see it, it should be self-explanatory, as it reads like English pretty well.
This syntax requires Python 2.7 or greater.
In Python 3, there is only dict.items(), not iteritems() so you would use:
filtered_dict = {k: v for k, v in d.items() if filter_string in k}
You can use the built-in filter function to filter dictionaries, lists, etc. based on specific conditions.
filtered_dict = dict(
filter(lambda item: filter_str in item[0], d.items())
)
The advantage is that you can use it for different data structures.
If I have a dictionary of students (key) and their averages (value), how can I create a function to help me return only the students with averages above 90?
How to filter dictionary by value?
How to filter a nested dict by key?
Filter Dataframe by Dictionary Values
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.com