[Tutor] creating dictionary from a list

eryksun eryksun at gmail.com
Sat Apr 13 23:29:01 CEST 2013


On Fri, Apr 12, 2013 at 7:52 PM, Saad Bin Javed <sbjaved at gmail.com> wrote:
> Hi, I'm using a script to fetch my calendar events. I split the output at
> newline which produced a list 'lst'. I'm trying to clean it up and create a
> dictionary with date:event key value pairs. However this is throwing up a
> bunch of errors.
>
> 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', '', '']

Don't forget to handle entries with times such as "Sat Apr 13   1:00pm".

I think it would be simpler in the long run to use a module that
parses iCalendar files. Your calendar application should support
exporting to iCalendar (.ics, .ical).

http://en.wikipedia.org/wiki/ICalendar

Here's an example sorting the events in the Python event calendar:

    import urllib2
    import datetime

    # https://pypi.python.org/pypi/icalendar
    import icalendar

    pyevent_url = (
      'http://www.google.com/calendar/ical/'
      'j7gov1cmnqr9tvg14k621j7t5c%40'
      'group.calendar.google.com/public/basic.ics')

    pyevent_ics = urllib2.urlopen(pyevent_url).read()
    pyevent_cal = icalendar.Calendar.from_ical(pyevent_ics)

You need a key function to sort the VEVENT entries by DTSTART:

    def dtstart_key(vevent):
        try:
            dt = vevent['dtstart'].dt
        except KeyError:
            dt = datetime.datetime.min
        if isinstance(dt, datetime.date):
            dt = datetime.datetime.combine(dt, datetime.time.min)
        return dt

If dt is a datetime.date, this key function converts it to a
datetime.datetime set to midnight (datetime.time.min). If the DTSTART
field is missing it uses datetime.datetime.min (0001-01-01 00:00).

Use walk('vevent') to show only the VEVENT entries in the calendar
(i.e. filter out VTODO, VJOURNAL, etc):

    events = sorted(pyevent_cal.walk('vevent'), key=dtstart_key)

The last event (index -1) is PyCon DE 2013 on 14 Oct:

    >>> events[-1]['description']
    vText(u'<a href="https://2013.de.pycon.org/">PyCon DE 2013</a>')

    >>> events[-1]['dtstart'].dt
    datetime.date(2013, 10, 14)


More information about the Tutor mailing list