-2

Below is my code

qas = [
    ["Apple","Red"],
    ["Banana", "Yellow"],
    ["Berries","Blue"]
]
answer_choices = {
    "a" : "Red",
    "b" : "Yellow",
    "c" : "Blue"
}
Answers_count = 0

for qa in qas :
    print("Choose from")
    for k,v in answer_choices.items() :
        print("("+k+") "+" "+v)
    ans=input("\nWhat color is "+ qa[0]+" : ")
    if answer_choices.get(ans) == qa[1] :
        print("Correct \n")
        Answers_count += 1
    else :
        print("Wrong \n")
print("You got "+str(Answers_count)+" correct")

Answers are expected to be printed as (a), (b), (c)

Some how order in which answer choice key value pairs printing is changing with the order of keys in qas.

Please suggest

KVT
  • 1
  • 1
    Dict keys follow insertion order only since CPython 3.6. You must be using an earlier Python version if that is not the case for you. See https://stackoverflow.com/questions/5629023/the-order-of-keys-in-dictionaries for a solution. – blhsing Jan 03 '20 at 23:37

1 Answers1

0

Python dictionary are not keeping the insertion order of the elements, it's not having a lexicographic ordering as well. You can try using an OrderedDict in order to keep the insertion order (not lexicographic one).

Another suggestion will be to replace the answer_choices with a list of tuples where the first argument will be the answer key while the seconds one will be the choose.

answer_choices = [("a", "Red"), ("b", "Yellow"), ("c", "Blue")]
    for k,v in answer_choices:
        print("(" + k + ") " + " " + v)
Amiram
  • 1,227
  • 6
  • 14