Rorschach
Rorschach

Reputation: 3802

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)

Upvotes: 0

Views: 83

Answers (2)

ForeverLearner
ForeverLearner

Reputation: 2103

from collections import defaultdict
p = defaultdict();

p[(2,2,'A')] = 1.0

p[(2,4,'NN')] = 1.5

print p
>> defaultdict(None, {(2, 4, 'NN'): 1.5, (2, 2, 'A'): 1.0})

This is an amazing library that helps you hold tuples (or even another frozen_dict, only criteria is that key needs to be hashable) as 'Keys' for the dictionary object.

Now, if you want to verify the elements:

In [8]:p.has_key((2, 4, 'NN'))
Out[8]: True
In [11]: p.values()
Out[11]: [1.5, 1.0]

To list all your keys for the dictionary:

In [13]: p.keys()
Out[13]: [(2, 4, 'NN'), (2, 2, 'A')]

You will love it!!

Upvotes: 1

Pankaj Singhal
Pankaj Singhal

Reputation: 16043

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}
>>> 

Upvotes: 3

Related Questions