Predicting the iteration order of a dictionary

In Python 3.7 and later, a dictionary remembers the order in which its keys were inserted. Consider this program, which records signal colours and then prints the keys of the dictionary.


Python
d = {}
d["red"] = 1
d["blue"] = 2
d["green"] = 3
d["red"] = 10
del d["blue"]
d["blue"] = 5
d["amber"] = 4
for key in d:
    print(key)


Arrange the keys in the order the loop prints them, from first printed to last printed.

  1. 1.

    blue

  2. 2.

    red

  3. 3.

    amber

  4. 4.

    green

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Dictionaries Questions: