python filter and sort list of orderedict from xml2dict
Question: i have a question on sorting xml2dict outcome. i have a xml like this:

Python 2.7

    
    
    <schedule>
      <layout file="12" fromdt="2015-07-25 00:42:35" todt="2015-09-02 02:54:14" scheduleid="34" priority="0" dependents="30.jpg,38.mp4,39.mp4"/> 
      <layout file="10" fromdt="2015-08-25 00:42:32" todt="2015-09-02 02:54:03" scheduleid="34" priority="1" dependents="30.jpg,38.mp4,39.mp4"/> 
    </schedule>
    

in which i use the following code to import to py:

    
    
    dict_schedule_xml  = xmlFileToDict(filename)
    layoutList.append(dict_schedule_xml['schedule']['layout'])
    

layoutList like below:

    
    
    [[OrderedDict([(u'@file', u'12'), (u'@fromdt', u'2015-07-24 00:42:35'), (u'@todt', u'2015-09-02 02:54:14'), (u'@scheduleid', u'34'), (u'@priority', u'0'), (u'@dependents', u'30.jpg,38.mp4,39.mp4')]), OrderedDict([(u'@file', u'10'), (u'@fromdt', u'2015-08-25 00:42:32'), (u'@todt', u'2015-09-02 02:54:03'), (u'@scheduleid', u'34'), (u'@priority', u'1'), (u'@dependents', u'30.jpg,38.mp4,39.mp4')])]]
    

and i want to filter out some unwanted entry as execute follow:

    
    
    dict_filtered_layout_list =  [s for s in layoutList if (onAirSchedule(s['@fromdt'],s['@todt']))]
    dict_filtered_layout_list =  sorted(dict_filtered_layout_list, key=lambda k: k['@priority'], reverse = True)
    

using the following self-defined function:

    
    
     def onAirSchedule(fromdt, todt):
            dt_now = datetime.now()
            fromdt = datetime.strptime(fromdt,'%Y-%m-%d %H:%M:%S')
            todt   = datetime.strptime(todt,'%Y-%m-%d %H:%M:%S')
            return (fromdt < dt_now < todt) 
    

I wonder everytime i got the error

    
    
      File "xibo_reader.py", line 91, in on_modified
        dict_filtered_layout_list =  [s for s in layoutList if (onAirSchedule(s['@fromdt'],s['@todt']))]
    TypeError: list indices must be integers, not str
    

I would like to have help on this as i don't know much on ordereddict
behaviour...


Answer: From the update `layoutList` looks like a list of list of OrderedDict , so
when you directly try to do `for s in layoutList if
(onAirSchedule(s['@fromdt']` ,it causes error as lists cannot be accessed
using string, only integer indexes.

If you want `dict_filtered_layout_list` to be a single list of OrderedDict
with the filtered values, then you can iterate over the list of lists inside
`layoutList` to create that single list.

Example -

    
    
    dict_filtered_layout_list =  [s for list_orderedDict in layoutList for s in list_orderedDict if (onAirSchedule(s['@fromdt'],s['@todt']))]
    dict_filtered_layout_list =  sorted(dict_filtered_layout_list, key=lambda k: k['@priority'], reverse = True)
    

