Simple quiz using a dictionary.

I thought I’d share a really simple program that uses Python’s “dictionary” data type.

If you want to read all about dictionaries, head over to the relevant section on python.org.

The basic idea of a dictionary is that it’s a way to store data. But instead of using indexes to identify elements in the list, we can use a wide range of different things as “keys”.

Here’s a really silly example.

a = dict()
# Use strings as key and value.
a["big"] = "huge"
# Use integers and floating point numbers.
a[5] = 8.2
a[3.14] = "pi"
# Use a tuple as the key and a boolean as the value.
a[(1,2)] = True
# Use a function as a value.
def plus1(x):
.. return x+1
..

Here’s what happens when we use those keys to extract items from the dictionary.

dict

So, as you can see, you can use plenty of different data types as the keys and values in a Python dictionary!

I am going to use a dictionary in a very simple way here. Let’s say we have to write a program that does a simple quiz. We could store questions and answers in a pair of lists, or even in a 2d list. But then we would have to access them using array notation (numbers in square brackets). With a dictionary we can use one string (the question) as the “key” which will link with another string (the “value” – in our case the answer).

Here’s the code.

"""quiz.py - simple quiz program."""

def main():
"""Set up the quiz."""

# The questions and answers are in this dictionary.
qs = {"What's the capital of England? ":"London",
"What's the third planet in the Solar System? ":"Earth",
"Who wrote \"Great Expectations\"? ": "Charles Dickens",
"Who sang \"Someone Like You\"? ":"Adele",
"Who is the current Doctor Who? ":"Peter Capaldi",
"Who is the sheriff in \"The Walking Dead\"? ": "Rick Grimes",
"Which metal is liquid at room temperature? ": "Mercury",
"Who plays Katniss in \"The Hunger Games\"? ": "Jennifer Lawrence",
"Which element combines with hydrogen to make water? ": "Oxygen",
"What is the highest mountain in the UK? ": "Ben Nevis"}

print("*** Quiz ***\n")
name = input("Please enter your name: ").title()
print()
print("\nWell done {0}, you scored {1} out of {2}.".format(name, quiz(qs), len(qs)))

def quiz(qs):
"""Returns a score. Asks questions from qs dictionary."""
score = 0;
# Use the .items() method to get the key / value pairs.
for q,a in qs.items():
if input(q).lower() == a.lower():
score += 1
print("Correct.")
else:
print("Sorry, correct answer is \"{}\".".format(a))
return score

if __name__ == "__main__":
main()
Advertisements

Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: