Home > Software engineering >  Verifying if indexes exist in a python multi-dimensional array
Verifying if indexes exist in a python multi-dimensional array

Time:02-18

Checking on some code I see something like this:

// This snippet is from the variables display in VS code while debugging and psuedocode:
theIndex: (1, 1)
myDataa['aKeyPhrase'][a secondary group of arrays]

So the myData has a first index of 'aKeyPhrase' which is a variable that changes and is a unique string, like so:

aKeyPhrase = 'labelA'
aKeyPhrase = 'labelB', etc.

The second part of myData contains a set of numbers so theIndex: (1, 1) is referring to the first index and second index of the set:

// (1, 1) would be refering the numbers  24.0 and 18.0
{1: 24.0, 2: 10.0, 3: 34.0}
{1: 18.0, 2: 23.0, 3: 32.0}

Before I do anything the the myData I want to check if theIndex exists and if it is equal to '%' and do the following:

if theIndex not in myData[aKeyPhrase] or myData[aKeyPhrasel][theIndex] == '%':

The first part of that expression above is always false. It should be true since the indexes exist in the myData sample. How do I check this correctly?

CodePudding user response:

IIUC, theIndex is a tuple and myData[aKeyPhrase] is a list of dictionaries and for theIndex = (1, 2), 1 corresponds to the key of the first dict, and 2 is the key of the second dict, correct? In that case, in the if-condition, if theIndex not in myData[aKeyPhrase] will always return False. You could modify it as

if all(i in d for i, d in zip(theIndex, myData[aKeyPhrase])) or myData[aKeyPhrasel][theIndex] == '%'
  • Related