interstellar
interstellar

Reputation: 399

finding values not in a dictionary

I have three separate dictionaries

d1 = {'1': 1, '2': 2, '3': 3, '4' :4}
d2 = {'5': 5, '7': 7, '9': 9, '10' :10}
d3 = {'12': 12, '23': 23, '30': 30, '14' :14}

I want to take a line from a file and test if three columns have values present in those dictionaries. If the values from the three columns are not in the dictionaries, I want to print the line of the file that the non-matches correspond to. Here is what I have written so far:

OutputFileName = "results.txt"
OutputFile = open(OutputFileName, 'w')
import csv
with open('inputfile.txt') as f:
    reader = csv.DictReader(f,delimiter="\t")
    for row in reader:
        assign1 = row['assign1']
        assign2 = row['assign2']
        assign3 = row['assign3']
        if assign1 in d1: 

This is where I run into some confusion. I only want assignments that are not in the d1. This is some pseudo-type code for what I would want to do:

if assign1 not in d1:
    if assign2 not in d2:
        if assign3 not in d3:
            OutputFile.write(''+assign1+'\t'+assign2+'\t'+assign3+'\n')

Is there an easy way to do this with dictionaries? Should I be using else statements? I'm having trouble with the implementation of the else's in this case

Upvotes: 0

Views: 53

Answers (1)

tobias_k
tobias_k

Reputation: 82899

Not 100% sure what you are asking. As I understand the question, you want to know how best to add an else clause to this complex three-fold if statement.

The best way would be not to have three if statements, but only one and use and to combine the conditions.

if assign1 not in d1 and assign2 not in d2 and assign3 not in d3:
    OutputFile.write(''+assign1+'\t'+assign2+'\t'+assign3+'\n')
else:
    # stuff to do when not in all three dicts

You could also transform the condition a bit, in case you find this to be more intuitive:

if not (assign1 in d1 or assign2 in d2 or assign3 in d3):

And you could also get rid of that not by swapping the if and the else case.

Upvotes: 1

Related Questions