根据字典检查变量,并打印剩余的字典内容

时间:2016-06-07 12:39:20

标签: python dictionary set theory

我想根据字典检查用户输入,然后打印字典中仍未存在的用户输入的值。

这是我的代码,它接受用户输入,将其与字典进行检查并将其发送到下面的打印功能。

    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)

这是我的函数,它打印在字典中找到的内容然后打印剩下的内容。

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

基本上我需要检查用户输入的功能(即A和B),然后打印字典中不是A和B的所有其他内容(即C,D和E)。基本上我正在运行“设置”和“补充”分析,用户输入该集合,然后打印该集合的补充。

最好的解决方法是什么?谢谢!

这是我的'笔记'字典。

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,
}

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您只需使用dict.pop()即可。 pop返回指定键的值,然后将其从字典中删除。指定的密钥不存在于字典中,默认情况下它将返回None。

a_dict = {'a': 1, 'b': 2, 'c': 3}

print(a_dict.pop('a'))
>> 1
print(a_dict)
>> {'c': 3, 'b': 2}

答案 1 :(得分:1)

使用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:
            print(element)

例如:

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

enter pitch 1
three
enter pitch 2
five
enter pitch 3
one
enter pitch 4
five
enter pitch 5
Done
The complement is
two
four
six
seven

请注意,基础字典数据结构不是dict,而是set。这是因为您并不真正需要键值对的键。由于您实际拥有的字典是dict,因此您可以删除密钥并将其转换为一组,如下所示:

dictionary = set(dictionary.values())

根据您对问题所做的编辑,词典中的值类型与您从用户输入的值的类型不匹配。具体来说,您获得str s,但是您有一个int字典。您可以将字典转换为一组str或从用户检索int

将字典从一组int转换为一组str可以按如下方式完成:

dictionary = {str(i) for i in dictionary}

(你应该在dictionary = set(dictionary.values())之后执行上面一行)

从用户而不是int中检索str可以按如下方式进行:

int(input("enter pitch {}".format(i + 1)))

而不是

str(input("enter pitch {}".format(i + 1)))
相关问题