Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 604
Pete Avatar asked Dec 03 '10 17:12

Pete


People also ask

What can be keys in Python dictionary?

Strings, numbers, and tuples work as keys, and any type can be a value. Other types may or may not work correctly as keys (strings and tuples work cleanly since they are immutable). Looking up a value which is not in the dict throws a KeyError -- use "in" to check if the key is in the dict, or use dict.

Do Python dictionary keys have to be strings?

The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples.

Do dictionary keys have to be integers?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.

Can you have a key without value Python?

There is no such thing as a key without a value in a dict. You can just set the value to None, though.


1 Answers

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:     try:         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.

like image 66
kindall Avatar answered Oct 08 '22 19:10

kindall