In article <[EMAIL PROTECTED]>, james_027 <[EMAIL PROTECTED]> 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'. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA -- http://mail.python.org/mailman/listinfo/python-list