-2

For a list of dictionaries, let's say:

[{'points':50, 'time': '5:00', 'year': 2010}, 
{'points': 25, 'time': '6:00', 'month': "february"}, 
{'points':90, 'time': '9:00', 'month': 'january'},
{'points_h1':20, 'month': 'june'}]

Is there a way to extract only the last dictionary from this?

0

2 Answers 2

2

-1 index will give the last element

d=[{'points':50, 'time': '5:00', 'year': 2010}, 
    {'points': 25, 'time': '6:00', 'month': "february"}, 
    {'points':90, 'time': '9:00', 'month': 'january'},
    {'points_h1':20, 'month': 'june'}]
    
    print(d[-1])
0

You can also reverse your list first , then access the first dictionary (which is actually the last dictionary ) .

lst_dicts = [{'points': 50, 'time': '5:00', 'year': 2010},
 {'points': 25, 'time': '6:00', 'month': "february"},
 {'points': 90, 'time': '9:00', 'month': 'january'},
 {'points_h1': 20, 'month': 'june'}]

res=lst_dicts[::-1] #reversing the list
print(res[0])

Not the answer you're looking for? Browse other questions tagged or ask your own question.