Some Python Tips and Tricks

05:08 Mon 21 Dec 2009
[, ]

Python Tips, Tricks, and Hacks at Siafoo is an excellent overview of useful Python knowledge. I was familiar with most of it but still think it’s worth reading over. I did learn a couple of new things, too.

I’ve found myself wanting the equivalent of list comprehensions (e.g. newlist = [do_something_to(item) for item in oldlist]) for dictionaries quite a few times, but never spent the time to figure out how to do that. The article does—you can use dict on a list of tuples that you’ve generated in a list comprehension in combination with dict.iteritems().

The first piece of new knowledge for me was that you can create new dictionaries not just with keyword arguments (d = dict(key1="value1", key2="value2")) and curly braces (d = {"key1": "value1", "key2": "value2"}) but also with a list of tuples of key/value pairs:

d = dict([("key1", "value1"), ("key2", "value2")])

That method of dictionary construction isn’t that useful… unless you’re dealing with large numbers of keys, or you’re moving between lists and dictionaries. You can go the other way, from a dictionary to a list of tuples, using dict.items() or dict.iteritems(). So here’s how to remove keys with empty values from a dictionary:

d = dict([key, value] for key, value in d.iteritems() if value)

That seems quite readable to me, and it’s definitely cleaner than the for and if statement approach that I used previously.

I also didn’t know about any and all, which can be used to evaluate whether any or all items in a list match a condition.

This next trick doesn’t come from the article, but was inspired by it: how to perform an operation on a specific set of keys in a dictionary only if those keys are in the dictionary. The obvious way:

for vehicle in ("planes", "trains"):
    if d.has_key(vehicle):
        d[vehicle] = d[vehicle].split(",")

There’s nothing wrong with that way, but I rather like being able to do this:

for vehicle in set(("planes", "trains")).intersection(d.keys()):
    d[vehicle] = d[vehicle].split(",")

I suspect that there are all kinds of operations that could be streamlined using various set functions.

(The last example could be reduced to a one-liner, but at that point we’re really losing readability:

d = dict(map(lambda (k,v): (k, d[k].split(",")) if k in ("planes", "trains") else (k, d[k]), d.iteritems()))

and it just doesn’t seem worth it.)

Leave a Reply