I have this list of dictionaries, for example:
JavaScript
x
3
1
list = [{a: "-1", month: 'January'}, {a: "0", month: 'February'}, {a: "1", month: 'March'},
2
{a: "2", month: 'April'}]
3
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:
JavaScript
1
2
1
[{a: "1", month: 'March'}, {a: "2", month: 'April'}]
2
if I choose:-1: it should return this:
JavaScript
1
2
1
[{a: "0", month: 'February'}, {a: "1", month: 'March'},{a: "2", month: 'April'}]
2
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:
JavaScript
1
16
16
1
list_ = [{'a': '-1', 'month': 'January'},
2
{'a': '0', 'month': 'February'},
3
{'a': '1', 'month': 'March'},
4
{'a': '2', 'month': 'April'}]
5
6
def forward(items,key,value):
7
# Note: enumerate returns the index and value of each list item
8
for i,d in enumerate(items):
9
if d[key] == value: # once the dictionary containing the key/value is found
10
return list_[i+1:] # return a slice of all items after that index
11
return []
12
13
print(forward(list_,'a','-1'))
14
print(forward(list_,'a','0'))
15
print(forward(list_,'a','1'))
16
Output:
JavaScript
1
4
1
[{'a': '0', 'month': 'February'}, {'a': '1', 'month': 'March'}, {'a': '2', 'month': 'April'}]
2
[{'a': '1', 'month': 'March'}, {'a': '2', 'month': 'April'}]
3
[{'a': '2', 'month': 'April'}]
4