List of Lists: return item

set testlist to {{"a", "Apple"}, {"b", "Ball"}, {"c", "Cat"}}

Can anyone tell me how to return the second item of an item of testlist based on the first item?
Example: If X is set to “a”, I want to return “Apple”. If X is set to “b”, I want to return “Ball”

Thanks for looking into this,
Slimjim5811

Here’s one option:

set findThis to "c"
set testList to {{"a", "Apple"}, {"b", "Ball"}, {"c", "Cat"}}

repeat with thisItem in testList
	if first item of thisItem is findThis then
		return second item of thisItem
	end if
end repeat

Edit: Here’s another (faster) option:

-- This string must not appear in testList! Strange characters should do the job.
set specialDelimiter to (ASCII character 11) & (ASCII character 0)
set findThis to "a"
set testList to {{"a", "Apple"}, {"b", "Ball"}, {"c", "Cat"}}

set ASTID to AppleScript's text item delimiters
set AppleScript's text item delimiters to {specialDelimiter}
set testList to testList as Unicode text

set AppleScript's text item delimiters to {findThis & specialDelimiter}
set testList to last text item of testList

set AppleScript's text item delimiters to {specialDelimiter}
set testList to first text item of testList
set AppleScript's text item delimiters to ASTID

return testList

Bruce, this is great! It helps me out more than you know!
Thanks so much!
slimjim5811

Hi,

If you have a big list, then something like the following is good also. You use a lookup table and a list with the goodies. Something like this:


property lu_table : "a	b	c"
property field_length : 2 -- tab included
property item_list : {"apple", "ball", "cat"}
--
display dialog "Enter a letter:" default answer "a"
set k to text returned of result
set o to (offset of k in lu_table)
if o is 0 then return
set i to (o div field_length) + 1
return item i of item_list

After a certain point in number of list items (something like 3,000 I think it was), text item delimiters gains an advantage. Offset is quick for medium sized lists if I remember right.

gl,