如何從字典數組中刪除字典?從字典數組中刪除值
我有一個這樣的字典數組:var posts = [[String:String]]()
- 我想用特定的鍵刪除字典,我將如何繼續?我知道我可以通過執行Array.removeAtIndex(_:)
或字典鍵從key.removeValue()
中刪除標準數組中的值,但字典數組更加棘手。
在此先感謝!
如何從字典數組中刪除字典?從字典數組中刪除值
我有一個這樣的字典數組:var posts = [[String:String]]()
- 我想用特定的鍵刪除字典,我將如何繼續?我知道我可以通過執行Array.removeAtIndex(_:)
或字典鍵從key.removeValue()
中刪除標準數組中的值,但字典數組更加棘手。
在此先感謝!
如果我理解你的問題正確的,這應該工作
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"]
]
*/
由於兩個你的字典和包裹數組是值類型,只是修改循環內的post
將修改字典的副本(我們創造了它通過聲明它使用var
),所以得出結論,我們需要將值設置爲index
到字典的新修改版本
This Works!非常感謝! – askaale
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)
所有詞典可以在行動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)
第一詞典可以在行動here看到這個代碼。
你是什麼意思的「我想刪除具有特定鍵的字典」?如果你有一個3字典的數組,其中2個有'foo'鍵,你希望它們全部被刪除嗎?只是第一個? – Alexander
@AMomchilov我想用特定鍵'foo'去除字典,因爲我知道字典數組中的所有鍵都是唯一鍵。 – askaale