Rorschach Rorschach - 1 day ago 3
Python Question

algorithm python datastructure

I am making a datastructure that basically acts like a python dictionary but it has 3 keys and one ouput.

For instance I have a nXn matrix and a few tags that possibly go with it.

So my pseudocode acts like:

my_dict[(2, 2, NN)] = 1.0
my_dict[(2, 4, NN)] = .12
my_dict[(0, 1, VP)] = .14
my_dict[(1, 1, VB)] = 1.0


What kind of data structure in python would work for that? (what should my_dict be)

Answer

Python dict can store tuples as keys but with a condition that it has to be hashable.

And, tuple is hashable if the elements inside the tuple are hashable.

So, if all of your 3 keys are hashable, then you don't need to make another data structure, instead, you can use the dict itself.

>>> my_dict = {}
>>> my_dict[(2, 2, 'NN')] = 1.0
>>> my_dict[(2, 4, 'NN')] = .12
>>> my_dict[(0, 1, 'VP')] = .14
>>> my_dict[(1, 1, 'VB')] = 1.0
>>> my_dict
{(0, 1, 'VP'): 0.14, (2, 4, 'NN'): 0.12, (2, 2, 'NN'): 1.0, (1, 1, 'VB'): 1.0}
>>> 
Comments