逐一比较字典中的一项与字典中的另一项

时间:2018-10-21 21:10:33

标签: python python-3.x dictionary

目前,我正在做一个作业,我必须将答案键(词典)与学生(词典)的答案进行比较。我必须计算出有多少学生答案与答案键匹配并返回该值。我意识到我当前的代码是将一个完整的字典与另一个字典进行比较,如果它们都相等,则它将返回一个值,但如果不相等,则返回0。我只是不确定如何修复它,因此会返回一个数那个匹配。

这是我当前的代码。这是上一个忘记添加的函数。

def index_responses(responses):
results = {}
count = 1
for answer in responses:
    """
    makes a dictionary containing the responses of the student
    and mapping it to a key of Q" " depending on wht number question it is.
    """
    results["Q" + str(count)] = answer[0]
    count += 1
return results

My current for this problem

1 个答案:

答案 0 :(得分:-1)

假设两个词典的键(此处为prompt)相同,或者至少对于答案词典中的每个键,都有一个匹配的响应提示,那么您可以像这样对它们进行计数

count = 0
for prompt, response in responses.items():
    if response == answers.get(prompt, None):
        count += 1
return count