Reputation: 695
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:
Upvotes: 0
Views: 266
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
Reputation: 113950
my_dict['key1'] = my_dict['key2'] = SomeObject
should work fine i would think
Upvotes: 2
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