AlexC AlexC - 2 years ago 63
Python Question

Check variables against a dictionary, and print the dictionary contents remaining

I want to check user inputs against a dictionary, and then print the values that still exist in the dictionary that were not inputed by the user.

Here's my code that takes user input, checks it against the dictionary and sends it to the print function below.

elif choice == '7':
print("Enter at least 4 pitches")
set1 = str(input("Enter first pitch: "))
set2 = str(input("Enter second pitch: "))
set3 = str(input("Enter third pitch: "))
set4 = str(input("Enter fourth pitch: "))
set5 = str(input("Enter fifth pitch or type 'Done': "))
if set5 == 'Done':
setset1 = f(set1)
setset2 = f(set2)
setset3 = f(set3)
setset4 = f(set4)

setc4(setset1, setset2, setset3, setset4)

Here's my function that prints what was found in the dictionary and then prints what is left.

def setc4(vset1, vset2, vset3, vset4):
print(" ")
print("The complement of the four note set")
print(vset1, vset2, vset3, vset4)

Basically I need the function to check user input (i.e. A and B) and then print everything else in the dictionary that's not A and B (i.e. C, D and E). Essentially I'm running a 'set' and 'complement' analysis, where the user inputs the set and then the complement of that set is printed.

What's the best way of going about this? Thanks!

Here's my 'notes' dictionary.

notes = {
'Bs': 0,
'C': 0,
'Cs': 1,
'Db': 1,
'D': 2,
'Ds': 3,
'Eb': 3,
'E': 4,
'Fb': 4,
'Es': 5,
'F': 5,
'Fs': 6,
'Gb': 6,
'G': 7,
'Gs': 8,
'Ab': 8,
'A': 9,
'As': 10,
'Bb': 11,
'B': 11,

Answer Source

Use the difference function to compute set difference.

number_of_inputs = ...
inputs = []
dictionary = {...}

def print_diff():
    for i in range(number_of_inputs + 1):
        inputs.append(str(input("enter pitch {}".format(i + 1))))
    if inputs[-1] == 'Done':
        del inputs[-1]
        diff = dictionary.difference(set(inputs))
        print('The complement is ')
        for element in diff:

For example:

>>> number_of_inputs = 4
>>> dictionary = {'one', 'two', 'three', 'four', 'five', 'six', 'seven'}
>>> print_diff()

enter pitch 1
enter pitch 2
enter pitch 3
enter pitch 4
enter pitch 5
The complement is

Note that the underlying dictionary data structure is not a dict but a set. If what you have is a actually a dict (i.e., key-value pairs), since all you need is the set of values, you can convert it to a set as follows:

dictionary = set(dictionary.values())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download