Hyacinth Bracken
Hyacinth Bracken

Reputation: 53

Filtering a list in python with many key-value pairs

I have a list that looks like this:

commands = [
{'command': "start app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "read log", 'action': "monitor", 'max-threshold': False, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False},
{'command': "kill app", 'action': "monitor", 'max-threshold': True, 'zero-failcount': True, 'started': True, 'stopped': False, 'failed': False}
]

And I would like to filter so that only a few cases are seen in the new list. For example, only those with max-threshold with true, zero-failcount true, etc. How do I do this? I'm using Python 2.7.

Upvotes: 2

Views: 54

Answers (3)

f5r5e5d
f5r5e5d

Reputation: 3706

you can make a list of k, v pairs to test for (doesn't have to be list of tuples)

hav = [('max-threshold', True), ('zero-failcount', True)]

[d for d in commands if all([d[k] == v for k, v in hav])]

Upvotes: 0

Umang Gupta
Umang Gupta

Reputation: 16450

Use filters b = list(filter(lambda x: x['max-threshold']==True, a))

Read more here : http://book.pythontips.com/en/latest/map_filter.html

Upvotes: 0

Raghav M
Raghav M

Reputation: 153

Use a list comprehension.

For example, something like:

[command for command in commands if command['max-threshold']]

Upvotes: 2

Related Questions