Another python thing I forget: dictionary construction

| | No TrackBacks

I am always forgetting how to do dictionary construction. Here is a piece of code I restructured for a friend. Notice that the dictionary is created from a sequence of tuples. (Slightly modified from the original for better pretty-printing.)

def slug_to_lower(fn):
    """
    Decorator to lowercase string arguments to a function.
    """
    import string
    def is_string(x):
        return isinstance(x, str) or isinstance(x, unicode)
    def trans(x):
        return (x if not is_string(x) else string.lower(x))
    def wrapped(*args, **kwargs):
        neo_args = [trans(x) for x in args]
        tuple_list = [(k,trans(v)) for k,v in kwargs.items()]
        neo_kwargs = dict(tuple_list)
        return fn(*neo_args, **neo_kwargs)
    return wrapped

No TrackBacks

TrackBack URL: http://www.iwebthereforeiam.com/cgi-bin/mt/mt-tb.cgi/1501

Leave a comment

Verification (needed to reduce spam):

Pages

OpenID accepted here Learn more about OpenID
Powered by Movable Type 4.32-en

About this Entry

This page contains a single entry by Hugh Brown published on June 5, 2009 11:34 AM.

The things I don't know about python was the previous entry in this blog.

Recent projects is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.