Welcome, guest | Sign In | My Account | Store | Cart

Want to get a value from a dictionary but want to make sure that the value exists in the dictionary? Then use the incredibly useful get method.

Python, 12 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
d = {'key':'value',}

# how you might write a test to pull out 
# the value of key from d
if d.has_key('key'):
  print d['key']
else:
  print 'not found'

# a much simpler syntax
print d.get('key', 'not found')
print d.get('foo', 'not found')

An amazingly simple syntax explained in the core python docs, but its surprising how many people dont know about it. This is especially common in Zope when pulling variables out of the REQUEST dict.