0

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)

3
  • Are you asking how you'd implement this? You could hash the keys, then just use a hash map. Commented Dec 1, 2016 at 6:05
  • Looks similar to accessing a numpy array Commented Dec 1, 2016 at 6:06
  • A dictionary key can be any hashable object. A tuple containing your 3 'keys' is an acceptable key, as long as the 3 items in the tuple are also hashable. Commented Dec 1, 2016 at 6:15

2 Answers 2

3

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}
>>> 
Sign up to request clarification or add additional context in comments.

Comments

1
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!!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.