Skip to content
Advertisement

Filter list of dictionaries from a value and get items forward [closed]

I have this list of dictionaries, for example:

list = [{a: "-1", month: 'January'}, {a: "0", month: 'February'}, {a: "1", month: 'March'},
        {a: "2", month: 'April'}]

So how would it be if I wanted to get the values of the list from an element that I choose. If I choose a:0, it should return all elements of this forward. It would be like this:

[{a: "1", month: 'March'}, {a: "2", month: 'April'}]

if I choose:-1: it should return this:

[{a: "0", month: 'February'}, {a: "1", month: 'March'},{a: "2", month: 'April'}]

Also, how would it be if it is proposed that the same selection be included in the list?

Advertisement

Answer

Here’s a function to walk the list and return all the items after the dictionary containing a certain key/value:

list_ = [{'a': '-1', 'month': 'January'},
         {'a': '0', 'month': 'February'},
         {'a': '1', 'month': 'March'},
         {'a': '2', 'month': 'April'}]

def forward(items,key,value):
    # Note: enumerate returns the index and value of each list item
    for i,d in enumerate(items):
        if d[key] == value:      # once the dictionary containing the key/value is found
            return list_[i+1:]   # return a slice of all items after that index
    return []

print(forward(list_,'a','-1'))
print(forward(list_,'a','0'))
print(forward(list_,'a','1'))

Output:

[{'a': '0', 'month': 'February'}, {'a': '1', 'month': 'March'}, {'a': '2', 'month': 'April'}]
[{'a': '1', 'month': 'March'}, {'a': '2', 'month': 'April'}]
[{'a': '2', 'month': 'April'}]
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement