Python dictionary keys besides strings and integers?

Anyone have some neat examples of dictionaries with some interesting keys (besides the canonical string or integer), and how you used these in your program?

I understand all we need for a key is something hashable, meaning it must be immutable and comparable (has an __eq__() or __cmp__() method).

A related question is: how can I quickly and slickly define a new hashable?


Let's go for something a bit more esoteric. Suppose you wanted to execute a list of functions and store the result of each. For each function that raised an exception, you want to record the exception, and you also want to keep a count of how many times each kind of exception is raised. Functions and exceptions can be used as dict keys, so this is easy:

funclist = [foo, bar, baz, quux]

results    = {}
badfuncs   = {}
errorcount = {}

for f in funclist:
        results[f] = f()
    except Exception as e:
        badfuncs[f]   = e
        errorcount[type(e)] = errorcount[type(e)] + 1 if type(e) in errorcount else 1

Now you can do if foo in badfuncs to test whether that function raised an exception (or if foo in results to see if it ran properly), if ValueError in errorcount to see if any function raised ValueError, and so on.

Need Your Help

Why does this sed command not match whitespace?

bash sed grep whitespace

This bash script is supposed to remove leading whitespace from grep results:

Using different methods of System.DirectoryServices.ActiveDirectory.Domain

active-directory powershell-v2.0 directoryservices

The static method of GetCurrentDomain() works without issue but, when I try to use another method such as FindDomainController(), I receive a MethodNotFound exception error.

% height without the height of the parent

css responsive-design

Is it possible to give a % height to a div without knowing the height of the parent? or better say, if the height of the parent changes. If this is not possible: What is the better way to have a t...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.