Using the dict(enumerate(x)), we get the { (index, value) }. Instead, I need { (value, index) }.
So, I've written this code...
idx= { n:i for i, n in enumerate(x)}
It works with some inputs and fails with others. Here's an input where it is failing.
x= [73,74,75,71,69,72,76,73]
, Why is it failing? and what should be done?
We know that for:
The result:
is "bad" for at least the first key in the dictionary. The reason it is bad (as others have pointed out) is that there are duplicate entries in the list
xand as we process them we are conceptually doing:We don't know what you actually expect for the key of
73. I think there is a good chance you want the value0but perhaps you want the value[0, 7]showing both indexes of73in the original list.The other wrinkle is not knowing how the additional item
99(occurring after the duplicated73) should be assigned a value. Do we keep the existing index entry8or do we want that to be a new7effectively replacing the duplicate?Determining how to get some other result is fairly straight forward and I'll give you several things you can try.
Option 1:
I want the keys to have their actual first list indexes:
Option 2:
I want the keys to have their first list indexes but if there is a duplicate, I just want to pretend it did not exist:
Option 3:
I want to capture the fact that there could be duplicates in the original list by setting the values in the resulting dictionary to a list of original indexes.