Reputation: 1199
How I can remove a dict from an array of dictionaries?
I have an array of dictionaries like so: var posts = [[String:String]]()
- and I would like to remove a dictionary with a specific key, how would I proceed? I know that I can remove a value from a standard array by doing Array.removeAtIndex(_:)
or a dictionary key by doing key.removeValue()
, but an array of dictionaries is more tricky.
Thanks in advance!
Upvotes: 1
Views: 5380
Reputation: 63264
let input = [
[
"Key 1" : "Value 1",
"Key 2" : "Value 2",
],
[
"Key 1" : "Value 1",
"Key 2" : "Value 2",
],
[
"Key 1" : "Value 1",
"Key 2" : "Value 2",
"Key 3" : "Value 3",
],
]
let keyToRemove = "Key 3"
//keep dicts only if their value for keyToRemove is nil (meaning key doesn't exist)
let result = input.filter{ $0[keyToRemove] == nil }
print("Input:\n")
dump(input)
print("\n\nAfter removing all dicts which have the key \"\(keyToRemove)\":\n")
dump(result)
You can see this code in action here.
var result = input
//keep dicts only if their value for keyToRemove is nil (meaning key doesn't exist)
for (index, dict) in result.enumerate() {
if (dict[keyToRemove] != nil) { result.removeAtIndex(index) }
}
print("Input:\n")
dump(input)
print("\n\nAfter removing all dicts which have the key \"\(keyToRemove)\":\n")
dump(result)
You can see this code in action here.
Upvotes: 3
Reputation: 5466
If I understood you questions correctly, this should work
var posts: [[String:String]] = [
["a": "1", "b": "2"],
["x": "3", "y": "4"],
["a": "5", "y": "6"]
]
for (index, var post) in posts.enumerate() {
post.removeValueForKey("a")
posts[index] = post
}
/*
This will posts = [
["b": "2"],
["y": "4", "x": "3"],
["y": "6"]
]
*/
Since both your dictionary and the wrapping array are value types just modifying the post
inside of the loop would modify a copy of dictionary (we created it by declaring it using var
), so to conclude we need to set the value at index
to the newly modified version of the dictionary
Upvotes: 4