Daniel Daniel - 6 months ago 9
Swift Question

Remove a key from a dictionary for a given value

How can I remove a key from a dictionary where the value is X? I need a dictionary.removeKeyForValue(...) function.

I'd like to optimise the following code. I have a text which is associated with a certain category and a dictionary that associates all keywords to categories. Although my text is already categorised I'd like check whether it should fall into a different category.

let text = "he said hello and then ran away" // This is taken from the "activity" category
// Dictionary associating keywords to categories
let categoryRules = ["hi" : "greeting", "hello" : "greeting", "jogging" : "activity", "joy" : "feeling"]

let keywords = Array(categoryRules.keys)
// Make out of text an Array of words.
let textWordArray = text.lowercaseString.characters.split{$0 == " "}.map(String.init)

// I SHOULDN'T HAVE TO GO THROUGH THE KEYS ASSOCIATED WITH "ACTIVITY" BECAUSE TEXT IS ALREADY IN IT.
for keyword in keywords {
// If text contains the rule
if let index = textWordArray.indexOf(keyword) {
// Get the associated category
if let category = categoryRules[keyword] {
print("The text should fall into the category of \(category)")
break
}
}
}

Answer

To remove all keys from a dictionary with a certain value, you can use a for loop with where clause to select the keys to remove and then assign nil to remove them:

var categoryRules = ["hi" : "greeting", "hello" : "greeting", "jogging" : "activity", "joy" : "feeling"]

for (key, value) in categoryRules where value == "greeting" {
    categoryRules[key] = nil
}

print(categoryRules)  // ["jogging": "activity", "joy": "feeling"]