Re: code to refer to a dictionary with and without nested dictionaries

With the caveat that I'm not clear on what you're trying to do, you almost never want to do what you're trying to do.  Taking your naturally nested data and flattening it for convenience is called denormalization, and 99% of the time you end up looking back and going "you know, this was a terrible mistake" even though it seemed convenient in the moment.  The right answer to a question like this is to write a class which exposes helper methods for convenient access, then hand that ownership of the dictionary.

Now, if you're just asking "how do I access nested dictionaries", you just:

dictionary['a']['b']

And you're done.

And if the question is "how do I let a user access this dictionary from the command line with convenient dot notation", the answer is that you:

class InvalidKeyException(Exception):
    pas

def read_impl(d, keys):
    if len(keys) == 0:
        return d
    k = keys[0]
    rest = keys[1:]
    if k not in d:
        raise InvalidKeyException()
    new_d = d[k]
    return read_limpl(new_d, rest)

def read(d, keys_str):
    keys = keys_str.split(".")
    return read_impl(d, keys)

Or something along those lines, I didn't test it.

-- 
Audiogames-reflector mailing list
Audiogames-reflector@sabahattin-gucukoglu.com
https://sabahattin-gucukoglu.com/cgi-bin/mailman/listinfo/audiogames-reflector
  • ... AudioGames . net Forum — Developers room : Zarvox via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : Zarvox via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : camlorn via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : Zarvox via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : camlorn via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : Zarvox via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : camlorn via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : Zarvox via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : camlorn via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : Zarvox via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : Zarvox via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : camlorn via Audiogames-reflector
    • ... AudioGames . net Forum — Developers room : Zarvox via Audiogames-reflector

Reply via email to