8

Is it reasonable to use objects as keys to a dictionary in django? I have done so and it works. But I am wondering if this is best practice, or if it is going to make difficulties I don't foresee right now.

I am working on a project which deals with educational standards. I have dictionaries with a structure along the lines of {Subject:[Standards]}. The model for subject looks something like:

class Subject(models.Model):
  subject = models.CharField(max_length=255, unique=True)

  def __unicode__(self):
    return self.subject

Is it okay to use the objects from this model as keys to my dictionaries, or should I be using a string represenation, such as Subject.subject instead?

If so, does the unicode method affect this? When I tried using Subject.subject as the key, I got things like {u'Math': [<Subject: Students can perform calculations.>]} Using objects as keys, it looks like {<Subject: Math>: [<Standard: Students can perform calculations.>]}

This is a followup to a question I asked yesterday about using None as a dictionary key.

Community
  • 1
  • 1
japhyr
  • 1,710
  • 2
  • 18
  • 24

4 Answers4

13

Mutable objects shouldn't really be used as dictionary keys. That said, this works because the base model class defines __hash__ in terms of the model's primary key, which is unlikely to change. But I would prefer to use the pk directly as the key.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Is this as simple as `def __hash__(self): return self.id`? If so, why does that need to be made explicit? Or do you mean I should define my dictionaries as `{subject.id:[standard.id]}`? – japhyr Aug 12 '11 at 16:29
  • This has the same idea as Alexandru's response, but is a little more specific. – japhyr Aug 12 '11 at 18:49
3

It depends how you want to use them. I'd suggest a simpler approach though:

The keys of the dictionaries could be the Model's primary key.

Alex Plugaru
  • 2,209
  • 19
  • 26
-1

Assuming the objects implement a good hash function I'd say that there's nothing wrong with using objects as keys, but that is just my personal opinion.

Exelian
  • 5,749
  • 1
  • 30
  • 49
-1

It would be better to use string representation since, when you will need to do looks up you will need to write out all that stuff, which will be a pain, plus if in the future you want to change your unicode representation you will have to find a way of rewriting the old unicode to do look ups.

Goodluck.

Mahdi Yusuf
  • 19,931
  • 26
  • 72
  • 101