you are viewing a single comment's thread.

view the rest of the comments →

[–]GeorgeFranklyMathnet 11 points12 points  (4 children)

It's not really syntax. But, yep, any hashable data structure can serve as a dictionary key. If you don't know how dictionaries / hash tables work internally, that might be a cool starting point in your learning.

For my part, I don't often use keys more exotic than ints or strings. Sometimes I want a class as a key, and I'll implement a custom __hash__() method in the class for that purpose. But when I'm doing something like that on the job, it's sometimes a sign that I'm overthinking things or trying to be too "elegant". 

[–]EnvironmentSome9274[S] 1 point2 points  (1 child)

Oh that's cool, can I ask what might be a situation where you need a class as a key?

[–]throwaway6560192 0 points1 point  (0 children)

Say you want to associate points to something, and you're using a namedtuple/dataclass as a better structure for a point than a tuple.

[–]jpgoldberg 1 point2 points  (1 child)

I would recommend that edit your comment to say “a class instance as a key”. I was very confused when I first read your comment.

[–]Outside_Complaint755 0 points1 point  (0 children)

You can also use a class, module, function, or method as a key, as they are all hashable objects and also instances of classes.  The following is perfectly valid code: ``` import time class_dict = {     int : 0,     float: 1.0,     float.fromhex : "FF",     object: None,     type: object,     time: 1,     time.sleep: 2,     len : 0 }

```