Tuesday, 14th June 2011
Dictionary.get()
Like enumerate, I'm not sure that this can be rightly called a trick since it's just a built-in function, but it's one that I wasn't aware of until long after I first needed it. Using a dictionary's get()
function allows you to automatically check whether a key is in a dictionary and return a default value if it isn't.
For example:
>>> numbers = {1: 'one', 2:'two', 3:'three'} >>> print numbers.get(1, 'Number not defined') one >>> print numbers.get(4, 'Number not defined') Number not defined
This is useful in all sorts of situations. One common situation in which I find it useful is when you want to get counts of the numbers of items in a group of items, for example, if you want to create a histogram. For example, to count the frequency of letters in a string:
my_string = "I want to get the counts for each letter in this sentence" counts = {} for letter in my_string: counts[letter] = counts.get(letter, 0) + 1 print counts
Here, for each letter in my_string, you are getting the number of counts for that letter; if that letter hasn't yet been added to the counts dictionary, then the 0 is returned.
Comments
Great tips. Thanks.
PS - looks like I misspelled my email on my previous comment.
Post new comment