string formatting with missing dictionary key 
Author Message
 string formatting with missing dictionary key

Hi,
A nice feature of later versions of python is the ability to get and set
undefined keys/values in dictionaries (dict.get,dict.setdefault).

However, this mechanism doesn't seem to be usable directly for a case in
which I am interested. I have an application in which I have a
formatting 'template' and a dictionary from which I get values for the
template.
In certain situations, there is a dictionary that doesn't have one or
more keys specified in the formatting string. In these cases, I get the
expected 'KeyError'.

As a very simple example, consider

mdict = {'a':1, 'b':2, 'c':3}
fline = "%(a)s ; %(d)s ; %(e)s" % mdict

Suppose you want any undefined keys to have the value 'default', i.e.

fline == "1 ; default ; default"

As far as I can see, there is no direct way to use .get/.setdefault to
do something like

"%(a)s ; %(d)s ; %(e)s" % mdict.setmissingkeyval('default')

so I have come up with the following workaround:

 >>> mdict = {'a':1, 'b':2, 'c':3}
 >>> fline = ''
 >>> while not fline:
...   try:
...     fline = "%(a)s ; %(d)s ; %(e)s" % mdict
...   except KeyError,e:
...     dummy = mdict.setdefault(e.args[0],'default')

Is there a better or more Pythonic way to do this?

Thanks for your help.

-g



Sat, 02 Jul 2005 01:11:53 GMT  
 string formatting with missing dictionary key
(Requires Python 2.2)

class D(dict):
    def __getitem__(self, item):
        if not self.has_key(item): return "default"
        return super(D, self).__getitem__(item)

print "%(a)s ; %(d)s; %(e)s" % D({'a':1, 'b':2, 'c':3})



Sat, 02 Jul 2005 03:20:31 GMT  
 string formatting with missing dictionary key


Quote:
> Hi,

> Is there a better or more Pythonic way to do this?

> Thanks for your help.

> -g

Perhaps subclassing an UserDict that returns a default value on a missing
key may do the job you expect.

Quote:
>>> from UserDict import UserDict
>>> class MyDict(UserDict):

...  def __getitem__(self, k):
...   return self.data.get(k, 'no data')
...

Quote:
>>> d = {'one' : 1, 'two': 2}
>>> md = MyDict(d)
>>> md['one']
1
>>> md['two']
2
>>> md['something_else']
'no data'

--Gilles


Sat, 02 Jul 2005 07:14:54 GMT  
 string formatting with missing dictionary key

Quote:

> Hi,
> A nice feature of later versions of Python is the ability to get and set
> undefined keys/values in dictionaries (dict.get,dict.setdefault).

> However, this mechanism doesn't seem to be usable directly for a case in
> which I am interested. I have an application in which I have a
> formatting 'template' and a dictionary from which I get values for the
> template.
> In certain situations, there is a dictionary that doesn't have one or
> more keys specified in the formatting string. In these cases, I get the
> expected 'KeyError'.

> As a very simple example, consider

> mdict = {'a':1, 'b':2, 'c':3}
> fline = "%(a)s ; %(d)s ; %(e)s" % mdict

> Suppose you want any undefined keys to have the value 'default', i.e.

> fline == "1 ; default ; default"

> As far as I can see, there is no direct way to use .get/.setdefault to
> do something like

> "%(a)s ; %(d)s ; %(e)s" % mdict.setmissingkeyval('default')

> so I have come up with the following workaround:

>  >>> mdict = {'a':1, 'b':2, 'c':3}
>  >>> fline = ''
>  >>> while not fline:
> ...   try:
> ...     fline = "%(a)s ; %(d)s ; %(e)s" % mdict
> ...   except KeyError,e:
> ...     dummy = mdict.setdefault(e.args[0],'default')

> Is there a better or more Pythonic way to do this?

> Thanks for your help.

> -g

Hi gyro

some more lines at the beginning,
but then, i think a little bit more Pythonic:

Quote:
>>> class myDict:

...     def __init__(self,default='default'):
...             self.mdict={}
...             self.default=default
...     def __setitem__(self,key,value):
...             self.mdict[key]=value
...     def __getitem__(self,key):
...             return self.mdict.get(key,self.default)
...     def keys(self):
...             return self.mdict.keys()
...     def values(self):
...             return self.mdict.values()
...     def items(self):
...             return self.mdict.items()
...     def update(self,dict):
...             self.mdict.update(dict)
...

# An Example

Quote:
>>> mdict=myDict('AnyDefaultValue')
>>> mdict.update({'a':1,'b':2,'c':3})
>>> mdict.items()

[('a', 1), ('c', 3), ('b', 2)]
Quote:
>>> mdict

<__main__.myDict instance at 0x00D7AE40>
Quote:
>>> fline = "%(a)s ; %(d)s ; %(e)s" % mdict
>>> fline

'1 ; AnyDefaultValue ; AnyDefaultValue'

Remark, i think <def keys>, <def values>, <def items> are not nessesarily
to implement.

Cheers Peter!



Sat, 02 Jul 2005 07:13:14 GMT  
 string formatting with missing dictionary key

Quote:
> (Requires Python 2.2)

> class D(dict):
>     def __getitem__(self, item):
>         if not self.has_key(item): return "default"
>         return super(D, self).__getitem__(item)

> print "%(a)s ; %(d)s; %(e)s" % D({'a':1, 'b':2, 'c':3})

>  <from Jeff Epler>

>>>>>>> from UserDict import UserDict
>>>>>>> class MyDict(UserDict):

> ...  def __getitem__(self, k):
> ...   return self.data.get(k, 'no data')
> ...

> --Gilles

>>>>class myDict:

> ...        def __init__(self,default='default'):
> ...                self.mdict={}
> ...                self.default=default
> ...        def __setitem__(self,key,value):
> ...                self.mdict[key]=value
> ...        def __getitem__(self,key):
> ...                return self.mdict.get(key,self.default)
> ...        def keys(self):
> ...                return self.mdict.keys()
> ...        def values(self):
> ...                return self.mdict.values()
> ...        def items(self):
> ...                return self.mdict.items()
> ...        def update(self,dict):
> ...                self.mdict.update(dict)
> ...

> Cheers Peter!

Thanks Jeff, Gilles, and Peter!
Looks like subclassing dict/UserDict or creating a new dict class is the
way to go.

-g



Sat, 02 Jul 2005 20:49:54 GMT  
 
 [ 5 post ] 

 Relevant Pages 

1. Get dictionary-keys used to format a string

2. Integer and String Dictionary Keys for Fast Access

3. String formatting with two dictionaries?

4. Extracting list of keys from 2-key dictionary

5. Dictionary to string and back to dictionary??

6. format specifiers in format string param.

7. Missing dictionary files

8. Dictionaries and Collections of keys

9. Importing multiople keys into dictionary

10. All components of the primary key must be linked - Dictionary Relationship

11. Cookbook: Associating multiple values with each key in a dictionary

12. How to get a key from dictionary?

 

 
Powered by phpBB® Forum Software