Snippets

Here are some code Python code snippets that may help when retrieving data through the API:

Sort Returned Data

Methods like page.files(), site.categories(), site.pages(), or user.sites() return data as a list of dictionaries in an arbitrary order. If you want to step through the pages in a specific order, you might want to sort the returned list by one of the dictionary keys. To do this, use the following code:

from operator import itemgetter
.
.
list_of_dicts.sort(key=itemgetter('dict-key'))

For example, to sort a list returned by site.pages() by category, and within each category by page name, use

list_of_pages.sort(key=itemgetter('name'))
list_of_pages.sort(key=itemgetter('category'))

Above code works, because Python's sort method is “stable,” i. e. once sorted by 'name' it will keep this order when sorting by 'category'.

Note that using ….sort(key=itemgetter('full_name')) will not work as expected as the 'full_name' of pages with no category is page-name, not _default:page-name and thus pages with no category will not be sorted together.

Also note that sort() operates by side effect — it modifies the list in place and does not return the sorted list.

Remove None Values from List of Dictionaries

As it may be easier to work with the data returned by the API if it doesn't contain any None values (e. g. you cannot concatenate a string with a None value), you may want to remove (i. e. replace with something else) any None values present.

The following code snippets replaces all None values with the string '(None)'.

pages = s.site.pages({'site': //site-name//, 'category': //category-name//})
for p in pages:
  for k in p.iterkeys():
    if p[k]==None:
      p[k]='None'

Convert List of Dicts to Wikidot Code

This snippet is not ready yet.

from operator import itemgetter
 
P = s.site.categories({'site': 'xml-api'})
P.sort(key=itemgetter('name'))
print ['* '+site['name']+'\n' for site in P]

prints
['* _default\n', '* admin\n', '* doc\n', '* nav\n', '* search\n', '* system\n']
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License