I want to keep track of a relationship between a number and a string. I want each item in the pair to act as a key that points to the other value, such that I could get the string provided the number or the number provided the string, and I want them to be linked such that if either the number or the string changes they still correctly point to the corresponding element.
My first attempt was to use a simple list:
ids = [
"id1", # 0
"id2", # 1
"id3" # 2
]
# getting id from number is trivial
string = ids[1]
# getting the number is also pretty easy
number = ids.index("id2")
The problem with this implementation is that the numeric keys are not guaranteed to be contiguous; meaning the list would have to be impractically large over wide numeric ranges, and unused values would have to be set to None
or similar, plus the performance penalty of linearly searching through a huge list of mostly nothing.
Given these limitations, a pair of dictionaries seems more applicable:
number_to_string = { 1: "A" }
string_to_number = { "A": 1 }
However, I want the two values to be dynamically linked, so if one pair changes the other is reflected as well. With this method any time I make a change with one I have to manually change it in the other:
# change (1, "A") to (1, "B")
number = 1
new_id = "B"
old_id = number_to_string[number]
number_to_string[number] = "B"
del string_to_number[old_id]
string_to_number[new_id] = number
print(number_to_string[1]) # "B"
It would also be nice to combine the two dictionaries as one, since they are conceptually linked together. The syntax I want would probably look more like:
link_structure = ... # something
link_structure.set_pair(1, "A")
link_structure.get_linked(1) # "A"
link_structure.get_linked("A") # 1
link_structure.set_pair(1, "B")
# and so on
Basically I want the advantages of dictionary representation but across two keys that are linked to each other instead of a value. Does Python have anything out-of-the-box to achieve this more elegantly, or should I just use the double dict method and roll my own class?