Bala
Bala

Reputation: 19

accessing the dictionary elements inside a list

I have a list of dictionaries:

 [{'start': '09:00', 'end': '11:00'}, {'start': '12:30', 'end': '12:45'}, {'start': '13:15', 'end': '14:00'}, {'start': '15:00', 'end':'16:45'}, {'start': '16:55', 'end': '17:00'}]

I have to fetch the value of first dictionary of value 'end' and the next dictionary of 'start' everytime:

for each_slot in free_slots: for key in each_slot.items(): if key=='end': print(key.val())

I expect my loop should fetch everytime this kind of output my first loop should fetch the first dictionary 'end':11:00 and start:12:30 and the second iteration should get 'end':12.45 and start:13:15. But I am getting an error

Upvotes: 0

Views: 65

Answers (3)

Praveenkumar
Praveenkumar

Reputation: 2182

You can do something like below. You can get all the start and end from source data, into a separate list and then shift the start to 1 position and zip both the list.

data = [{'start': '09:00', 'end': '11:00'}, {'start': '12:30' , 'end': '12:45'}, {'start': '13:15', 'end': '14:00'}, {'start': '15:00', 'end':'16:45'}, {'start': '16:55', 'end': '17:00'}]

starts = list(map(lambda d : d['start'], data))[1:]
ends = list(map(lambda d : d['end'], data))

for v in zip(ends, starts):
    print(v)

Output:

('11:00', '12:30')
('12:45', '13:15')
('14:00', '15:00')
('16:45', '16:55')

Upvotes: 1

Mohannad_
Mohannad_

Reputation: 89

another solution:

l=[{'start': '09:00', 'end': '11:00'}, {'start': '12:30' , 'end': '12:45'}, {'start': '13:15', 'end': '14:00'}, {'start': '15:00', 'end':'16:45'}, {'start': '16:55', 'end': '17:00'}]
    for i in  range(0,len(l)-1):
     print('end:',l[i]['end'],'Start:',l[i+1]['start'])

Upvotes: 0

Amit
Amit

Reputation: 2090

You may try the below and see if it suits your needs.

my_dict = [{'start': '09:00', 'end': '11:00'}, {'start': '12:30' , 'end': '12:45'}, {'start': '13:15', 'end': '14:00'}, {'start': '15:00', 'end':'16:45'}, {'start': '16:55', 'end': '17:00'}] 
processed_list = [{'start':my_dict[x]['start']} if x%2==1 else {'end':my_dict[x]['end']} for x in range(len(my_dict)) ]
print(processed_list)

The output as below.

[{'end': '11:00'}, {'start': '12:30'}, {'end': '14:00'}, {'start': '15:00'}, {'end': '17:00'}]                  

All the best.

Upvotes: 1

Related Questions