0
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?

variable
  • 8,262
  • 9
  • 95
  • 215

2 Answers2

1

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.

freakish
  • 54,167
  • 9
  • 132
  • 169
  • Or iterate over `range(1, max(dct) + 1)`? Assumes your book has no missing leaves. – jpp Oct 03 '19 at 15:35
  • Ok so in python 3.6 onwards, it is guaranteed that when using a for loop on a dict.items(), items will be retrieved in the order that they were inserted? And so if items were added in sequence they will be retrieved in same sequence? And that we must use sorted function only if the order of insertion is arbitrary and we want to retrieve in sorted manner? – variable Oct 12 '19 at 04:41
0
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.

a_r
  • 488
  • 6
  • 12