I have 2 data structures -
- list, and
List holds a bunch of keys. Dictionary has those same keys. As for the value of each key, I want to store the address of corresponding element in the list. What would this achieve: For a key, I would lookup the dictionary if the key is present or not. If key is present, then get the address of that element in the list and fetch/pop/append that element.
What do I store in the dictionary as the
value of each key using which I can get to that particular element in the list? Index of a key will change in the list. For example, I can pop an element out and insert it towards the end. So that makes the index of all the keys change in the dictionary. Hence, storing the absolute index is not what I want.
Example of the list, some operation on it and the resultant list. L = ['1', '2', '3']
Add '4' to list: L = ['1', '2', '3', '4'] Pop the last unused element: L = ['2', '3', '4'] Use the element '2': L = ['3', '4', '2'] Pop the last unused element: L = ['4', '2'] Add '1' to the list: L = ['4', '2', '1'] Add '5' to the list: L = ['4', '2', '1', '5'] Use '2' from the list: L = ['4', '1', '5', '2']
As you can see, the position of the elements are changing based on the operations performed. Using dictionary will help to avoid searching the list if I had the stored the address of the element in it.