Sorting a dictionary by numbered keys

Question: with action code, how can I sort a diction ary by number 1…20, etc., so that 10 does not show up was the first item in the list. For example, I want to sort this dictionary in numerical order. I tried ‘$Scale=$Scale.sort’ in a stamp, but it did not work.

10:Yes, another Hispanic, Latino, or Spanish origin - Spain;2:Yes, another Hispanic, Latino, or Spanish origin - Argentina;15:No;3:Yes, another Hispanic, Latino, or Spanish origin - Colombia;11:Yes, another Hispanic, Latino, or Spanish origin - Venezuela;4:Yes, another Hispanic, Latino, or Spanish origin - Ecuador;16:Prefer not to answer;5:Yes, another Hispanic, Latino, or Spanish origin - El Salvadore;12:Yes, Cuban;6:Yes, another Hispanic, Latino, or Spanish origin - Guatemala;13:Yes, Mexican, Mexican American or Chicano;7:Yes, another Hispanic, Latino, or Spanish origin - Other Country;8:Yes, another Hispanic, Latino, or Spanish origin - Panama;14:Yes, Puerto Rican;1:Yes, another Hispanic, Latino, or Spanish origin;9:Yes, another Hispanic, Latino, or Spanish origin - Peru

Dictionaries, like sets, cannot be sorted.

The reason for this is straightforward. Sets and dictionaries are designed to be efficient, and to that end they sort their contents. Because dictionaries know how their contents are arranged, they can more quickly located the value of a key, or tell you that some key has no value.

If you want to display the contents of a dictionary as a string, that’s easy to do.

  1. Get the keys to the dictionary: var:list theKeys=$Scale.keys;
  2. Sort the keys: theKeys = theKeys.sort
  3. Make a place to store the result: var:string result;
  4. Walk through the sorted keys:
theKeys.each(key) {
    result = result+key+"\t"+$Scale[key]+"\n";
    }
2 Likes

Great, thanks. This will work.

I’ve just updated aTbref’s page on the Dictionary-type (see heading ‘Dictionary sorting’) with a version of above in aTbRef’s more idiomatic form (to assist learners find the moving parts). The code is:

var:list vKeyList = $MyDictionary.keys;
vKeyList = vKeyList.sort; // Use .nsort if keys are numbers
var:list vSortResults; // Use List so it stays sorted
vKeyList.each(aKey){
	vSortResults+=(aKey+" | "+$MyDictionary[aKey]);
};
//Test
//$Text = vSortResults.format("\n"); 

Note that with keys like in the example of $Scale above, .sort is lexical so the keys order 1,10,2 not 1,2,10. To get the latter use List.nsort at line #2.

Once the pattern is understood, a shorter version could be (by collapsing some steps and chaining)

var:list vKeyList = $MyDictionary.keys.sort; // Use .nsort if keys are numbers
...etc.