0

I am creating a dictionary in python Flask that contains strings. It's order like this :

dict =  {01:'string1', 02:'string', 03:'string3',..., 10:'string10', 11:'string11'}

The order to sort is 0,1,2,...,9

Once I pass this dict to my javascript, the dictionary is order with this sort method :

dict =  {10:'string10', 11:'string11',...,01:'string1', 02:'string', 03:'string3' }

The sort order is 1,2,3,...,9,0

How can I keep my sort order when I pass a dictionary from python flask to JS

userHG
  • 567
  • 4
  • 29
  • Dictionaries(or objects in js) don't have an ordering for the keys, so ordering can't be guaranteed unless you switch it to an array. – Aplet123 Apr 02 '20 at 13:51
  • @Aplet123 - They do, but using that order is rarely if ever appropriate. – T.J. Crowder Apr 02 '20 at 13:52
  • JavaScript doesn't have dictionaries it has objects/JSON which are not guaranteed to be ordered. – Alex W Apr 02 '20 at 13:55
  • @AlexW - objects != JSON :-) And object properties have had order since 2015. (But as I said above: *Using it* is almost never a good idea...) – T.J. Crowder Apr 02 '20 at 13:57
  • 1
    Let's be really specific. Python dictionaries do not have order, as @Aplet123 mentioned. The sort order is not preserved after you create the dictionary. Your solution is to sort the object by key on the JavaScript side. Also not good practice to use `dict` builtin as a variable name. – Markus R Apr 02 '20 at 13:59
  • I never said objects were JSON :) but how is Python passing data to JS? And just because the ES spec added support for ordering doesn't mean the specific use case does which may be the case here? – Alex W Apr 02 '20 at 14:01
  • @AlexW - To me, "objects/JSON" reads as treating JSON as a synonym for "objects" (which is an error people make all the time). Fair enough if that's not what you meant. :-) – T.J. Crowder Apr 02 '20 at 14:09
  • Python does have insertion-ordered dictionaries from [3.6 onward](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6) but otherwise you need OrderedDict. – Alex W Apr 02 '20 at 14:22

1 Answers1

0

It's not a dictionary (on the JavaScript side), it's an object. Object properties have an order now (added in ES2015 and extended to more operations in ES2020), and assuming you created those properties on the object in the order 01, then 02, etc., the order you're seeing in your second example is the correct order for an object. That's because property names that are strings in canonical integer format (10, 11) come first, numerically, followed by any other properties (such as 01, 02, which aren't canonical integer strings because of the leading 0) in the order they were created.

If you want an arbitrary order, use an array or a Map. (Maps are ordered purely by the order their entries were added.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875