Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The following code works. It checks for the special case of a single key having a period in it. Then, it splits the key apart. For each subkey, it tries to fetch the value from a list-like context, then it tries from a dictionary-type context, then it gives up.</p> <p>This code also shows how to use unittest/nose, which is <em>highly</em> recommended. Test with "nosetests mysource.py".</p> <p>Lastly, consder using Python's built-in ConfigParser class, which is really useful for this type of configuration task: <a href="http://docs.python.org/library/configparser.html" rel="nofollow noreferrer">http://docs.python.org/library/configparser.html</a></p> <pre><code>#!/usr/bin/env python from nose.tools import eq_, raises context = { 'database': { 'port': 9990, 'users': ['number2', 'dr_evil'] }, 'admins': ['number2@virtucon.com', 'dr_evil@virtucon.com'], 'domain.name': 'virtucon.com' } def getitem(key, context): if isinstance(context, dict) and context.has_key(key): return context[key] for key in key.split('.'): try: context = context[int(key)] continue except ValueError: pass if isinstance(context, dict) and context.has_key(key): context = context[key] continue raise KeyError, key return context def test_getitem(): eq_( getitem('database', context), {'port': 9990, 'users': ['number2', 'dr_evil']} ) eq_( getitem('database.port', context), 9990 ) eq_( getitem('database.users.0', context), 'number2' ) eq_( getitem('admins', context), ['number2@virtucon.com', 'dr_evil@virtucon.com'] ) eq_( getitem('domain.name', context), 'virtucon.com' ) @raises(KeyError) def test_getitem_error(): getitem('database.nosuchkey', context) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload