Ben Mordecai
Ben Mordecai

Reputation: 695

Is it possible to use multiple keys for a single element in a dict?

I am writing my own function for parsing XML text into objects which is can manipulate and render back into XML text. To handle the nesting, I am allowing XML objects to contain other XML objects as elements.

Since I am automatically generating these XML objects, my plan is to just enter them as elements of a dict as they are created. I was planning on generating an attribute called name which I could use as the key, and having the XML object itself be a value assigned to that key.

All this makes sense to me at this point. But now I realize that I would really like to also save an attribute called line_number, which would be the line from the original XML file where I first encountered the object, and there may be some cases where I would want to locate an XML object by line_number, rather than by name.

So these are my questions:

  1. Is it possible to use a dict in such a way that I could find my XML object either by name or by line number? That is, is it possible to have multiple keys assigned to a single value in a dict?
  2. How do I do that?
  3. If this is a bad idea, what is a better way?

Upvotes: 0

Views: 266

Answers (3)

Andrew Latham
Andrew Latham

Reputation: 6132

Since dictionaries can have keys of multiple types, and you are using names (strings only) as one key and numbers (integers only) as another, you can simply make two separate entries point to the same object - one for the number, and one for the string.

dict[0] = dict['key'] = object1

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 113950

my_dict['key1'] = my_dict['key2'] = SomeObject

should work fine i would think

Upvotes: 2

NPE
NPE

Reputation: 500277

Yes, it is possible. No special magic is required:

In [1]: val = object()

In [2]: d = {}

In [3]: d[123] = val

In [4]: d['name'] = val

In [5]: d
Out[5]: {123: <object at 0x23c6d0>, 'name': <object at 0x23c6d0>}

I would, however, use two separate dictionaries, one for indexing by name, and one for indexing by line number. Even if the sets of names and line numbers are completely disjoint, I think this is a cleaner design.

Upvotes: 2

Related Questions