String formatting with dictionaries

Skip Montanaro skip at pobox.com
Thu Jul 1 10:31:09 EDT 2004


    Thomas> I am aware that I can make it work by changing e to 
    Thomas> e={'1':'one', '2': 'two'} 
    Thomas> but I do want to find out 

    Thomas> a) what is needed make it work in its current form, and

How about subclassing dict so that __getitem__ tries calling int() on the
key it's presented if it fails to find the key?

    class mydict(dict):
        ### untested! ###
        def __getitem__(self, key):
            try:
                return dict.__getitem__(self, key)
            except KeyError:
                try:
                    key = int(key)
                except ValueError:
                    raise
                else:
                    return dict.__getitem__(self, key)



    Thomas> b) why it does not work in the seemingly obvious way I have
    Thomas>    written it above

Because strings are not ints.

Skip




More information about the Python-list mailing list