Home > Software engineering >  Ignoring a value that is not in the Index List
Ignoring a value that is not in the Index List

Time:10-14

I have a file that does not contain all the same variables that I am checking for in my code I am getting a 'value is not in the Index' error obviously.

with open('valid.json', 'r') as validvals:
    valid = json.load(validvals)
    
valid_list=[col for col in df]
for k in valid.keys():
    if k not in valid_list:
        print ( f"The value {k} isn't recognized as a valid value." )

I have a print statement there for the time being just because I was testing to make sure that the rest of the code worked but basically it is read the column name of the df and comparing it to the key names in the JSON file which is the file I am comparing all my data to to find inconsistent matches for data cleaning purposes.

I have tried

col_list=[col for col in df]
key=list(valid.keys())
for k in key:
    if k not in col_list:
        del key[k]

but i am getting 'TypeError: list indices must be integers or slices, not str' I would like to ignore that values that are not in valid_list so the rest of the code will properly run.

CodePudding user response:

Here's the solution i found to work best for me:

col_list=[col for col in df]
key=list(valid.keys())
for k in key:
    if k not in col_list:
        key.remove(k)

CodePudding user response:

you can try this:

col_list=[col for col in df]
key=list(valid.keys())
new_key = []
for k in key:
    if k not in col_list:
        continue
    else:
        new_key.append(k)

and new_key is what you want.

CodePudding user response:

You can use this code:

data = {"a":1,"b":2}
keys = list(data.keys())
for i in keys:
    if i == "a":
        del data[i]
  • Related