2016-07-05 124 views
1

如何從字典數組中刪除字典?從字典數組中刪除值

我有一個這樣的字典數組:var posts = [[String:String]]() - 我想用特定的鍵刪除字典,我將如何繼續?我知道我可以通過執行Array.removeAtIndex(_:)或字典鍵從key.removeValue()中刪除標準數組中的值,但字典數組更加棘手。

在此先感謝!

+0

你是什麼意思的「我想刪除具有特定鍵的字典」?如果你有一個3字典的數組,其中2個有'foo'鍵,你希望它們全部被刪除嗎?只是第一個? – Alexander

+0

@AMomchilov我想用特定鍵'foo'去除字典,因爲我知道字典數組中的所有鍵都是唯一鍵。 – askaale

回答

3

如果我理解你的問題正確的,這應該工作

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到字典的新修改版本

+1

This Works!非常感謝! – askaale

2

刪除與給定的關鍵

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看到這個代碼。

+0

第一個代碼(我在找什麼)似乎不起作用。我嘗試使用此代碼,然後打印字典數組,但沒有運氣。數據未被刪除。這很奇怪.. – askaale

+0

在那個代碼片段下面有一個鏈接,顯示它工作正常 – Alexander