Sorting List of Dictionaries by keys

Hi guys,

I’m trying to created a SortedList from an array of Dictionaries containing Buffers and integers representing the midi note number associated with the sample inside the buffer.

I’m taking inspiration from this snipped of code I’ve found in the “SequenceableCollection” docs where elements can be sorted by keys:

(
a = [
    Dictionary[\a->5, \b->1, \c->62],
    Dictionary[\a->2, \b->9, \c->65],
    Dictionary[\a->8, \b->5, \c->68],
    Dictionary[\a->1, \b->3, \c->61],
    Dictionary[\a->6, \b->7, \c->63]
]
)
a.sortBy(\b);
a.sortBy(\c);

but my code is not working and I don’t know why.
Can you help me understanding what I’m doing wrong?

This is the samples folder I’m loading samples from (in case you are interested these are Creative Commons Sampling Plus 1.0 license samples I’ve taken from this link):

and this is my code (inside the do block there’s some logic to get the “midi note number” from the filename):

// 1. load samples from a folder
~buffers = SoundFile.collectIntoBuffers("path/to/folder", s);

// 2. create an empty the Array to be populated
~array = [];


// 3. populate the array with Dictionaries
(
~buffers.do{
	|item|
	var d = Dictionary.new;
	
	var string = PathName(item.path).fileNameWithoutExtension;
	// some logic the get the note name from the file name
	// and to calculate the associated midi number
	var output = string.findRegexp("[abcdefgABCDEFG]#?[0123456789]");
	var noteNameAll = output[0][1];
	var octNumber = noteNameAll.rotate(1)[0].asString.asInteger;
	var noteName = noteNameAll[0].asString;
	var isSharp = noteNameAll.contains("#");
	var midiNumber = (octNumber +1) * 12;
	switch( noteName,
		"c", { midiNumber = midiNumber+0; },
		"d", { midiNumber = midiNumber+2; },
		"e", { midiNumber = midiNumber+4; },
		"f", { midiNumber = midiNumber+5; },
		"g", { midiNumber = midiNumber+7; },
		"a", { midiNumber = midiNumber+9; },
		"b", { midiNumber = midiNumber+11; },
	);
	if(isSharp, {midiNumber = midiNumber + 1;});
	// some debug print
	[noteNameAll, noteName, isSharp, octNumber, midiNumber].postln;
	// adding key-value pairs to the dictionary 
	d.put("midi", midiNumber.asInteger);
	d.put("note", noteNameAll);
	// then add it inside the array
	~array = ~array.add(d);
}
)

// 4. this line gives me an error!
~array.sortBy(\midi);

You are putting “midi” (string), but sorting by \midi (symbol)

Cheers,

eddi

1 Like

Thank you @alln4tural for your reply!
nick