How is the order of request.form.items() determinded?

381 Views Asked by At

I want to print user-entered values to a file but every time I run it again, even with the same data (or no data at all), they are in a different order. This is the part of my .py file that does this:

for key, value in request.form.items():
    data = "%s=%s\n" % (key, shlex.quote(value))
    configfile.write(bytes(data, 'UTF-8'))

Here is an example of one output: (the first 3 lines of 40)

 IP=''
 cloud_radio=NO
 TO=''

Here is another example where I entered the exact same data: (again the first 3 lines out of 41)

key=''
port2=''
IP=''

Is it possible to set the order that they output in? OR make sure that the order is the same each time?

1

There are 1 best solutions below

0
On BEST ANSWER

In Python a dict is not ordered. You can sort the items by the order of their key with:

for key, value in sorted(request.form.items()): 
    ...

If you need a specific order, you can specify a key function to sorted