[Tutor] creating dictionary from a list
Saad Bin Javed
sbjaved at gmail.com
Sat Apr 13 16:34:49 CEST 2013
I ran into a bit of problem with my revised code based on Steven's
suggestions.
lst = ['', 'Thu Apr 04 Weigh In', '', 'Sat Apr 06 Collect
NIC', ' Finish PTI Video', '', 'Wed Apr 10
Serum uric acid test', '', 'Sat Apr 13 1:00pm Get flag from
dhariwal', '', 'Sun Apr 14 Louis CK Oh My God', '', '']
lst = filter(None, lst)
lst = [item.split(' ') for item in lst]
lst = [item for sublist in lst for item in sublist]
lst = filter(None, lst)
This code would produce:
['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI
Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm',
'Get flag from dhariwal', 'Sun Apr 14', ' Download Louis CK Oh My God']
dict = {}
for item in lst:
if item.startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):
dict.update({lst[lst.index(item)].lstrip():
lst[lst.index(item)+1].lstrip()})
print dict
Such a dictionary would only add the item next to the date as the value.
But from the list you can see 'Sat Apr 06' has two items on the agenda
while 'Sat Apr 13' show item and a time. So you can understand why such
a dict would be useless.
I want all agenda items joined as a comma delimited string and added to
the date key as a value. I've been mulling over how to go about it. One
idea was to get indices of dates in the list and add all items in
between them as values.
index_keys = [] #0, 2, 5, 7, 9
index_values = [] #1, 3, 4, 6, 8, 10
for item in lst:
if item.lstrip().startswith(('Mon','Tue','Wed','Thu','Fri','Sat','Sun')):
index_keys.append(lst.index(item))
else:
index_values.append(lst.index(item))
But I can't quite get it to understand that i want all items between
position 0 and 2 in the list to be assigned to item at 0 in the
dictionary and so forth.
Ideas?
More information about the Tutor
mailing list