dict = {1:'Page 1 contents', 2:'Page 2 contents', 3:'Page 3 contents'}
for pagenum, pagecontents in dict.items():
Does this code guarantee that pages will be processed in order 1, 2 and 3? If not, then what is the way to guarantee this?
dict = {1:'Page 1 contents', 2:'Page 2 contents', 3:'Page 3 contents'}
for pagenum, pagecontents in dict.items():
Does this code guarantee that pages will be processed in order 1, 2 and 3? If not, then what is the way to guarantee this?
The general answer is: there is no such guarantee. Before Python3.6 dicts were not guaranteed to have any ordering. Since Python3.7 dictionaries are guaranteed to be insertion ordered which is not necessarily the same thing that you expect. Unless the 1,2,3,... order actually is the insertion order (it is in your literal dict case, but typically you don't deal with literal dicts).
So here are few things you can do to be 100% sure:
If you need to keep the dict, then the fastest thing is to simply loop like this:
pagenum = 0
while True:
pagenum += 1
try:
pagecontents = dict[idx]
except KeyError:
break
// do stuff
cause you seem to know that keys are always numbers. Gaps and other irregular behaviour is a problem though. So if that's the case then you can sort before looping:
for pagenum, pagecontents in sorted(dict.items()):
// do stuff
although this is much, much slower.
Finally consider switching from dict to a structure that actually does support arbitrary ordering, like list.
dict = {1:'Page 1 contents', 2:'Page 2 contents', 3:'Page 3 contents'}
for pagenum, pagecontents in sorted(dict.items()):
This should help your cause.