faqts : Computers : Programming : Languages : Python : Snippets : Dictionaries

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

9 of 10 people (90%) answered Yes
Recently 8 of 9 people (89%) answered Yes

Entry

"Safe" dictionary

Oct 26th, 2006 04:21
alex novo, Nathan Wallace, unknown unknown, Hans Nowak, Snippet 345, Barry A. Warsaw


"""
Packages: basic_datatypes.dictionaries
"""
"""
    GH> This is ugly! Isn't there a better way to fill in just SOME of
    GH> the %(...)s values in a string and leave the rest as is?
Here's what we use in Mailman:
"""
from UserDict import UserDict   # added by PSST
class SafeDict(UserDict):
    """Dictionary which returns a default value for unknown keys.
    """
    def __init__(self, d=None):
        # optional initial dictionary is a Python 1.5.2-ism.  Do it 
this way
        # for portability
        UserDict.__init__(self)
        if d:
            self.update(d)
    def __getitem__(self, key):
        try:
            return self.data[key]
        except KeyError:
            if type(key) == StringType:
                return '%('+key+')s'
            else:
                return '<Missing key: %s>' % `key`