I'm loop through all items in a dictionary, use the syntax: for key, value in questions.items()
, where questions
is the dictionary name. This will assign key
to be the dictionary key, and value
to be the dictionary value.
Why I'm getting the error below?
line 13, in <module>
ans = input("What is the capital of " questions[value] " ? ")
KeyError: 'y'
q1 = input("Please enter a country: ")
a1 = input("Please enter its capital: ")
q2 = input("Please enter a country: ")
a2 = input("Please enter its capital: ")
questions = {q1 : a1, q2 : a2}
score = 0
for key, value in questions.items():
ans = input("What is the capital of " questions[value] " ? ")
if ans == questions[key]:
print("Correct!")
score = score 1
else:
print("Incorrect!!")
print("Final score is: ", score)
CodePudding user response:
You could save yourself a lot of confusion by naming your variables meaningfully. For example, in your loop, you could use
for country, capital in questions.items():
You obviously wouldn't write ans = input("What is the capital of " questions[capital] " ? ")
when you want to just use the capital. Dictionaries only map one way: you can only check for a country as a key, not a capital. capital
is not a valid key, so to avoid the error:
ans = input(f"What is the capital of {country}? ")
Using string summation is fine, but f-strings are nicer in my opinion, and sort of the de-facto convention since their introduction.
The whole point of iterating over items
is exactly that you don't have to do repeated lookups:
if ans == capital:
print("Correct!")
score = score 1
else:
print("Incorrect!!")
CodePudding user response:
Its cause your are iterating over a dictionary with dictionary.items()
which returns both the key and the value.
Then you are trying to retrieve the value from the dictionary by the value and not the key.
for key, value in questions.items():
ans = input("What is the capital of " value " ? ") # <-- Just use the value
if ans == questions[key]:
print("Correct!")
score = score 1
else:
print("Incorrect!!")
If you want to use the key to retrieve the value then use questions[key]
.
However I think what you are trying to do is the question is the key of the dictionary while the answer is the value.
In that case do
ans = input("What is the capital of " key " ? ")
CodePudding user response:
Try this out:
questions = {q1: a1, q2: a2}
score = 0
for key in questions:
ans = input("What is the capital of " key " ? ")
if ans == questions[key]:
print("Correct!")
score = score 1
else:
print("Incorrect!!")
print("Final score is: ", score)