I occasionally use dictionaries in my scripts but only in bits and pieces. So, just for learning purposes, I created a rudimentary database which I’ve included below.
I am not satisfied with the script segment entitled “Modify a dictionary by key value”. It works but I would like to eliminate the repeat loop. Also, I was unable to get the last script segment to work with a compound predicate and resorted to the use of two separate predicates. Thanks for any suggestions.
-- Revised 2022.05.19 to correct issues
use framework "Foundation"
use scripting additions
-- Create a mutable array of mutable dictionaries
set personList to {{firstname:"John", lastname:"Adams", age:60, occupation:"President"}, {firstname:"Samuel", lastname:"Adams", age:70, occupation:"Statesman"}, {firstname:"Thomas", lastname:"Jefferson", age:60, occupation:"President"}}
set personArray to current application's NSMutableArray's arrayWithArray:personList
-- Add a dictionary
set newRecord to {firstname:"Samuel", lastname:"Chase", age:80, occupation:"Supreme Court Justice"}
personArray's addObject:newRecord
set personList to personArray as list
-- Modify a dictionary by key value
set searchKey to "lastname"
set searchValue to "Chase"
set revisedData to {age:50, occupation:"Founding Father"}
set thePredicate to current application's NSPredicate's predicateWithFormat:"%K == %@" argumentArray:{searchKey, searchValue}
set theDictionary to personArray's filteredArrayUsingPredicate:thePredicate
if theDictionary's |count|() ≠ 1 then error "Multiple or no matches found"
(theDictionary's objectAtIndex:0)'s addEntriesFromDictionary:revisedData
set personList to personArray as list
-- Get dictionaries by key value (occupation in this case)
set searchKey to "occupation"
set searchValue to "President"
set thePredicate to current application's NSPredicate's predicateWithFormat:"%K == %@" argumentArray:{searchKey, searchValue} -- from Shane
set searchResults to (personArray's filteredArrayUsingPredicate:thePredicate) as list
-- Get dictionaries by two key values (firstname and lastname in this case)
set searchKeyOne to "firstname"
set searchValueOne to "Samuel"
set searchKeyTwo to "lastname"
set searchValueTwo to "Adams"
set thePredicate to current application's NSPredicate's predicateWithFormat:"%K == %@ AND %K == %@" argumentArray:{searchKeyOne, searchValueOne, searchKeyTwo, searchValueTwo}
set searchResults to (personArray's filteredArrayUsingPredicate:thePredicate) as list