a dict trick

Stargaming stargaming at gmail.com
Thu Aug 2 03:01:03 EDT 2007


On Thu, 02 Aug 2007 06:32:11 +0000, james_027 wrote:

> hi
> 
> for example I have this dictionary
> 
> dict = {'name':'james', 'language':'english'}

First of all, this is a bad name because it shadows (overwrites) the 
reference to the builtin constructor, `dict`.

> 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.

If you're using using Python 2.5, you could do this without `and`/`or` 
trickery::

    >>> d['name'] if 'name' in d else 'unknown'
    'james'
    >>> d['sex'] if 'sex' in d else 'unknown'
    'unknown'

But there are more elegant ways. For example, the `get` method::

    >>> d.get('name', 'unknown')
    'james'
    >>> d.get('sex', 'unknown')
    'unknown'

See the `Python Library Reference, 3.8: Mapping types <http://
docs.python.org/lib/typesmapping.html#l2h-294>` for more information on 
`dict` methods.

Or you could use the `collections.defaultdict <http://docs.python.org/lib/
defaultdict-objects.html>` type (new in 2.5, too), which I consider most 
elegant::

    >>> from collections import defaultdict
    >>> d2 = defaultdict(lambda:'unknown', d)
    >>> d2['name']
    'james'
    >>> d2['sex']
    'unknown'

HTH,
Stargaming




More information about the Python-list mailing list