If the keys have no duplicates (if these have than the problem is rather ambiguous anyway), and the keys are hashable (strings are hashable), we can use a dictionary:
thelist = [('look', 38),
('ganesh', 35),
('said', 30),
('tiger', 30),
('cat', 28)]
thedict = dict(thelist)
Now we can perform a lookup with:
thedict['look']
This will give us 38
, in case we lookup a key that is not present, like 'bobcat'
, then Python will raise a key error:
>>> thedict['bobcat']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'bobcat
We can thus handle it with:
ourkey = 'bobcat'
try:
ourvalue = thedict[ourkey]
except KeyError:
# do something in case not present
pass
Note: do not use variable names like list
, dict
, tuple
, etc. since you override references to the list
class.
Note: in case you want to use a default value instead when the lookup fails, you can use thedict.get(ourkey, defaultvalue)
, or in case that should be None
, we can use thedict.get(ourkey)
. Note that if such function returns None
, that does not per se means that the key was not found: it can mean that the key was not found, but it can also be the result of the fact that the key was associated with a None
value.