annoying dictionary problem, non-existing keys

Michele Petrazzo michele.petrazzo at TOGLIunipex.it
Thu Apr 24 15:43:38 CEST 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.
> 

That is one of python rules:
 >>> import this
(cut)
Explicit is better than implicit.
(cut)

php hide some thing that python expose.

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

You can simple modify the dict behavior:

 >>> class my_dict(dict):
...  def __getitem__(self, item):
...   if item in self:
...    return super(my_dict, self).__getitem__(item)
...   else:
...    return ''
...
 >>> d = my_dict()
 >>> d["a"]
''
 >>> d["a"] = 5
 >>> d["a"]
5
 >>>

Michele



More information about the Python-list mailing list