2

In Python, I am parsing an xml file into dictionary, using this module. The core of my code is very simple:

configdict = ConvertXmlToDict('tasks.xml')

for task in configdict['osmo_tasks']['tasks_entries']['entry']:
    print task['id'], task['due_date'], task['summary']

the above code will parse the xml file into dictionary and then iterate through tasks and print them. Obviously, it will print them in the same order that they were read from, the xml file:

1 736366 summary
2 735444 another summary
5 735796 blah

How can I print the lines sorted according to task['due_date'] ?

This is a sample xml file:

<?xml version="1.0" encoding="utf-8"?>
<osmo_tasks version="000212">
  <category_entries/>
  <tasks_entries>

    <entry>
      <id>1</id>
      <status>1</status>
      <due_date>736366</due_date>
      <due_time>53100</due_time>
      <summary>summary</summary>
    </entry>

    <entry>
      <id>2</id>
      <status>1</status>
      <due_date>735444</due_date>
      <due_time>55800</due_time>
      <summary>another summary</summary>
    </entry>

    <entry>
      <id>5</id>
      <status>0</status>
      <due_date>735796</due_date>
      <due_time>55800</due_time>
      <summary>blah</summary>
    </entry>

  </tasks_entries>
</osmo_tasks>
Martin Vegter
  • 136
  • 9
  • 32
  • 56

2 Answers2

6

Try the sorted built-in function: https://docs.python.org/2/library/functions.html#sorted

sorted can take any iterable and a key by which to sort. Here's an example similar to yours:

sorted_test.py

configdict = {
        'tasks': {
            'entries': [
                { 'id': 1, 'date': 736366 },
                { 'id': 2, 'date': 735444 },
                { 'id': 3, 'date': 735796 }
                ]
            }
        }

tasks = sorted([ t for t in configdict['tasks']['entries'] ], key=lambda task: task['date'])

print repr(tasks)

Result:

[{'date': 735444, 'id': 2}, {'date': 735796, 'id': 3}, {'date': 736366, 'id': 1}]
jparonson
  • 322
  • 1
  • 4
2

Use sorted with a custom key function key for sorting

Reference

Something like:

sorted(configdict,key=lambda x: x['due_date'])
aa333
  • 2,556
  • 16
  • 23