RDF nodes as Python dictionaries

I was recently looking for some code to wrap RDF nodes to Python objects / dictionnaries – something like activerdf in ruby – in order to manipulate RDF nodes easilly, and then use Jinja template engine to render SW documents in HTML.

I didn’t find anything[1] so I wrote a tiny module that does the job, using redland. By finding all (SPO) statements with the given node as subject, it creates a Python dictionnary with predicates as keys, and lists of object nodes as values (using a list even if there’s only one node in order to get something generic). And then, recurse – avoiding infinite loops – for each object.

Regarding literals, they are stored in 3 ways in the dictionnary:

  • First, using the “literals” key, to store the literal itself (with its datatype, lang and value);
  • Then, using the “strings” key, to store only literal values;
  • Finally, for each lang, using the “strings_lang” key, to store literal values for a given language.

It will also save the URI of resource nodes.

Eg with a DOAP file coverted to a python dict. Then, I can use something like node['doap_description'][0]['strings_fr'][0] to get the description of the project in french.

Finally, I just have to pass the dictionary to a Jinja template, and get my DOAP profile rendered as HTML. Result can be seen there.

The module, template and conversion script are available here.


[1] Edit 22/11: Actually there’s Sparta that seems to do what I needed

Leave a Reply

Your email address will not be published. Required fields are marked *