Useful python trick of the day: dict.get()

How often in Python have you written something like:

d[k] if k in d else "Default"

Admittedly this has gotten a lot shorter since the inclusion of ternary operators in Python, but did you know that Python provides a get method for dictionaries that allows you to provide a default?

d.get(k, "Default")

I only found out today when reviewing code. Exciting!

This entry was posted in hacking, programming, python. Bookmark the permalink.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>