a dict trick

Michael J. Fromberger Michael.J.Fromberger at Clothing.Dartmouth.EDU
Thu Aug 2 18:54:45 CEST 2007

In article <1186036331.304916.304020 at e9g2000prf.googlegroups.com>,
 james_027 <cai.haibin at gmail.com> 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.

Hi, James,

You might prefer:

  d = {'name': 'James', 'language': 'English'}

  value = d.get('sex', 'unknown')

This accomplishes what your above code does, using a method of the 
built-in dict object.

If you also wish to ADD the new value to the dictionary, you may also 
use the following:

  value = d.setdefault('sex', 'unknown')

This returns the same value as the above, but also adds the key 'sex' to 
the dictionary as a side-effect, with value 'unknown'.


Michael J. Fromberger             | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA

More information about the Python-list mailing list