What I’m trying to do:
Preserve the order of keys in a list of dictionaries when returned to the client from a server function.
The keys are getting jumbled somehow after being returned to the main form in certain reproducible cases, despite being put in the desired order server side.
I have not been able to find any reason to suspect that my code is the cause, and as far as I understand them, dictionary key order is preserved by default in Python 3.x. I wonder if you’d be able to help me get to the bottom of the mystery.
What I’ve tried and what’s not working:
My app allows the user to specify which metric columns (keys) they want in their csv (built from the list of dictionaries). The columns need to be displayed in the correct order for my users to be able to read them easily, so I want the keys in my list of dictionaries to be in a certain order.
Everything works beautifully most of the time (thank you Anvil!), except in a few certain cases, in which it consistently doesn’t work. Here is the flow of data, with the problem area italicised:
User inputs what they want client side → sent to the server → server gets what is needed via API and put into a list of dictionaries in desired order → [ list of dictionaries returned to client [keys become jumbled] → list of dictionaries sent to csv function ] → converted to csv media object server side → csv media object is returned to client to download, but the column order is unhelpful to the user due to the key jumbling.
When the user specifies certain metric columns to be included (returned in the list of dicts and converted to csv), the order of the keys in the list of dictionaries after it has been returned to client (viewed via print statement immediately after being returned) is jumbled despite being returned in the desired order by the server function - verified by print just before return.
One theory is that the keys become jumbled when a dictionary which has more than a certain number of keys is sent from server to client? In this case it’s about 12.
Code
Client side:
resultsDictList = anvil.server.call(‘main_program’, user_input_list, market, scope, results_per_seed, mode, get_cpc)
Server side:
resultsDictList when printed immediately before returning, has the keys in the desired order
Client side:
print(resultsDictList)
^^ The order of keys changed
I even wrote a server function especially to reorder the keys. It successfully reordered them server side, but when it sent them to the client, they were jumbled again! So it really looks like just being in the client is causing the keys in this list of dictionaries to become jumbled.