Case-insensitive dict, non-destructive, fast, anyone?

Ron_Adam radam2 at tampabay.rr.com
Fri Apr 1 12:37:40 EST 2005


On 01 Apr 2005 15:55:58 +0300, Ville Vainio <ville at spammers.com>
wrote:

>>>>>> "Daniel" == Daniel Dittmar <daniel.dittmar at sap.corp> writes:
>
>    Daniel> Ville Vainio wrote:
>
>    >> I need a dict (well, it would be optimal anyway) class that
>    >> stores the keys as strings without coercing the case to upper
>    >> or lower, but still provides fast lookup (i.e. uses hash
>    >> table).
>
>    Daniel> Store the original key together with the value and use a
>    Daniel> lowercase key for lookup.
>
>That's what I thought initially, but the strings take most of the
>space in dict and I didn't feel like doubling the size.
>
>It would be the "simplest thing that could possibly work", though.

Try access the keys indirectly though another dictionary.  That way
you don't have to change the original.

Lkeys = {}
for k dict.keys():
	Lkeys[ k.lower] = dict[k]

Then use:

value = dict[ Lkeys[ key.lower() ] ]

To get your value from the original dictionary.

Watch out for duplicate keys in differing case in the original dict. 


Ron




More information about the Python-list mailing list