a dict trick
Gary Herron
gherron at islandtraining.com
Thu Aug 2 03:11:45 EDT 2007
james_027 wrote:
> hi
>
> for example I have this dictionary
>
> dict = {'name':'james', 'language':'english'}
>
> value = 'sex' in dict and dict['sex'] or 'unknown'
>
> is a right pythonic of doing this one? I am trying to get a value from
> the dict, but if the key doesn't exist I will provide one.
>
> THanks
> james
>
>
This fails if 'sex' is in the dictionary and it's value happens to be
any of the values that evaluate to a boolean False. In that case you'll
get 'unknow' even though the key is in the dictionary.
However, python dictionaries provide a way to do this:
dict.get('sex', 'unknown')
looks up the value associated with the key if it exists, otherwise it
returns the provided default value.
You may also want to checkout the dictionary method setdefault which has
the functionality of get PLUS if the key is not found, it adds the
key,value pair to the dictionary.
Gary Herron
More information about the Python-list
mailing list