realFishSam
realFishSam

Reputation: 189

Index right to left instead of left to right Python

I have written an application. The goal is to read data from this dictionary (it is a dictionary because I have more lists within it, however they are not relevant to this question so I cut them out):

initialDictionary = {
    "xCoordinate": [2, 4, 6, 3, 6],
}

As seen, the xCoordinate 6 is a duplicate, so to get rid of the duplicate I do this:

affectedCoordinates = list(set(initialDictionary["xCoordinate"]))

This then results in a new list but without the duplicates.

[2, 3, 4, 6]

Now I want to find the index (location) of every item of affectedCoordinates in the original initialDictionary, to do this I have done this:

for affectedCoordinate in (affectedCoordinates):
    if affectedCoordinate in initialDictionary["xCoordinate"]:
        print(initialDictionary["xCoordinate"].index(affectedCoordinate))

However, this reads the original list within initialDictionary from left to right, so it prints:

0 3 1 2

This is wrong. I want the index of whatever duplicate is the farthest right in the initialDictionary list (read right to left instead of left to right). So the application should print this:

0 3 1 4

Here's my entire code:

initialDictionary = {
    "xCoordinate": [2, 4, 6, 3, 6],
    "state": [1, 1, 1, 1, 0]
}


affectedCoordinates = list(set(initialDictionary["xCoordinate"]))
print(initialDictionary["xCoordinate"])
print(affectedCoordinates)


for affectedCoordinate in (affectedCoordinates):
    if affectedCoordinate in initialDictionary["xCoordinate"]:
        print(initialDictionary["xCoordinate"].index(affectedCoordinate))

Upvotes: 0

Views: 656

Answers (2)

user2390182
user2390182

Reputation: 73470

Make a helper dict, using enumerate and a dict comprehension:

index = {x: i for i, x in enumerate(initialDictionary["xCoordinate"])}

This will store the last index for every unique value. Then you can use it similar to the index function:

for ac in affectedCoordinates:
    print(index[ac])

Upvotes: 1

Thierry Lathuille
Thierry Lathuille

Reputation: 24233

You should use a different approach. Using a set makes you lose any order in the initial data, and using index makes the whole process about O(n^2).

You can simply build a dict with the values as keys, and the last index of each value. It can be made simply with:

data = [2, 4, 6, 3, 6]
index_of_last = dict((val, index) for index, val in enumerate(data))
print(index_of_last)

# {2: 0, 4: 1, 6: 4, 3: 3}

You can get the values and indices separately by getting the keys and values of this dict:

print(index_of_last.keys())
print(index_of_last.values())

#dict_keys([2, 4, 6, 3])
#dict_values([0, 1, 4, 3])

Upvotes: 1

Related Questions