I’m trying to learn Python through Learn Python the Hard Way. I’m now on Exercise 39 and have a simple question. I tried to search online but couldn’t find any answers. Here’s the code from the exercise:
# create a mapping of state to abbreviation
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
print '-' * 10
# safely get a abbreviation by state that might not be there
state = states.get('Texas', None)
if not state:
print "Sorry, no Texas."
# get a city with a default value
city = cities.get('TX', 'Does Not Exist')
print "The city for the state 'TX' is: %s" % city
I don’t quite understand what None does in state = states.get('Texas', None). If it were used to tell Python that “there is no more,” then why couldn’t I just write state = states.get('Texas')? What do I need the extra None here? Thanks!
The
Nonehere is a default value fordict.get()telling python what to return if the key does not exist. It is a little superfluous in this case, asget()defaults toNonefor the second parameter.From the docs:
So it directly equivalent to
states.get('Texas')which is equivalent to:So in this case, where you are then simply checking if
statedoesn’t evaluate toTrue, it’s pointless, it’d be better to simply do the try/except and perform the action you want on the exception (unless for some reason you are getting back other values you are also filtering out, such as empty strings, which seems unlikely).The Python docs are detailed but clear, so in situations where you don’t know what an argument is, check the docs.