annoying dictionary problem, non-existing keys

Robert Bossy Robert.Bossy at jouy.inra.fr
Thu Apr 24 04:24:37 EDT 2008


bvidinli wrote:
> i use dictionaries to hold some config data,
> such as:
>
> conf={'key1':'value1','key2':'value2'}
> and so on...
>
> when i try to process conf, i have to code every time like:
> if conf.has_key('key1'):
>      if conf['key1']<>'':
>          other commands....
>
>
> this is very annoying.
> in php, i was able to code only like:
> if conf['key1']=='someth'
>
> in python, this fails, because, if key1 does not exists, it raises an exception.
>
> MY question:
> is there a way to directly get value of an array/tuple/dict  item by key,
> as in php above, even if key may not exist,  i should not check if key exist,
> i should only use it, if it does not exist, it may return only empty,
> just as in php....
>
> i hope you understand my question...
>   
If I understand correctly you want default values for non-existing keys. 
There are two ways for achieving this:

Way 1: use the get() method of the dict object:
    conf.get(key, default)

which is the same as:
    conf[key] if key in conf else default


Way 2: make conf a defaultdict instead of a dict, the documentation is 
there:
http://docs.python.org/lib/defaultdict-objects.html

Hope this helps,
RB



More information about the Python-list mailing list