Python complex dictionary keys
Question: My question pertains to dictionary keys. I want to set up a dictionary that
has 3 keys for any single object. The keys must be in order and can have a
wide range of values. For instance,

    
    
    dictionary = {(key1,key2,key3) : object}
    

key1 can be any value between 1 and 10 key2 can be any value between 11 and 20
key3 can be any value between 21 and 30

The order in which the keys are placed does matter.

More specifically, my keys correspond to a range of x,y,z cartesian
coordinates in which many objects are floating around in. I want to be able to
sort the relative position of the objects based off their x,y,z positions.

Is there any way to set this up or will I have to take a different approach?
Thanks for any help!


Answer: Sure you can, as well as to create single string key for this - just merge
string results for your keys like ','.join([k1,k2,k3])

[Read more about
dictionaries.](http://docs.python.org/2/tutorial/datastructures.html#dictionaries)

> dictionaries are indexed by keys, which can be any immutable type; strings
> and numbers can always be keys. Tuples can be used as keys if they contain
> only strings, numbers, or tuples; if a tuple contains any mutable object
> either directly or indirectly, it cannot be used as a key. You can’t use
> lists as keys, since lists can be modified in place using index assignments,
> slice assignments, or methods like append() and extend().

So you trying to use tuples as a keys and this is OK.

Note that dictionaries in python are not sorted. You can use
collections.OrderedDict for this. Also to build correct sorting use
[sort/sorted
functions](http://docs.python.org/2/library/functions.html#sorted) with
parameter key specified to sort the way you want.

EDITED sample:

    
    
    from itertools import product
    myDict = {}
    for x,y,z in product(range(10), range(10,20), range(20,30)):
        myDict[(x,y,z)] = sum([x,y,z])
    

