SHINTO JOSEPH
SHINTO JOSEPH

Reputation: 387

How to remove the keys of a dictionary where the values are null in swift 3

Hi I need to remove the dictionary keys which is having no values .I tried many codes but not working .I only need the dictionary with keys which have values and I need to do it in swift 3

["H": [], "X": [], "D": ["D1\r\n\r\n"], "J": ["J1\r\n"], "I": [], "M": [], "Z": [], "S": [], "A": ["A2"], "C": ["C2\r\n\r\n"], "N": [], "Y": [], "R": [], "G": [], "E": ["Emmm\r\n"], "V": [], "U": [], "L": [], "B": ["B2"], "K": ["King"], "F": [], "O": [], "W": [], "T": ["Test", "Test2"], "P": [], "Q": ["Queen"]]

Upvotes: 3

Views: 4022

Answers (2)

Nayana
Nayana

Reputation: 128

I tried this code and worked for me.

var dict: [String: [Any]] = ["H": [], "X": [], "D": ["D1\r\n\r\n"], "J": ["J1\r\n"], "I": [], "M": [], "Z": [], "S": [], "A": ["A2"], "C": ["C2\r\n\r\n"], "N": [], "Y": [], "R": [], "G": [], "E": ["Emmm\r\n"], "V": [], "U": [], "L": [], "B": ["B2"], "K": ["King"], "F": [], "O": [], "W": [], "T": ["Test", "Test2"], "P": [], "Q": ["Queen"]]
for (key, value) in dict where value.isEmpty {
   dict.removeValue(forKey: key)
}

Upvotes: 4

Sweeper
Sweeper

Reputation: 271810

I think you meant "remove the KVPs that have [] as values", not "remove the KVPs that have nil as values".

A call to filter would work, but it returns an array of tuples of KVPs so you gotta add them all to a new dictionary using a for loop.

let dict = ["H": [], "X": [], "D": ["D1\r\n\r\n"], "J": ["J1\r\n"], "I": [], "M": [], "Z": [], "S": [], "A": ["A2"], "C": ["C2\r\n\r\n"], "N": [], "Y": [], "R": [], "G": [], "E": ["Emmm\r\n"], "V": [], "U": [], "L": [], "B": ["B2"], "K": ["King"], "F": [], "O": [], "W": [], "T": ["Test", "Test2"], "P": [], "Q": ["Queen"]]
var newDict = [String: [String]]()
for (key, value) in dict.filter({ !$0.1.isEmpty }) {
    newDict[key] = value
}

Alternatively, you can do this by just looping through the dictionary once:

let dict = ["H": [], "X": [], "D": ["D1\r\n\r\n"], "J": ["J1\r\n"], "I": [], "M": [], "Z": [], "S": [], "A": ["A2"], "C": ["C2\r\n\r\n"], "N": [], "Y": [], "R": [], "G": [], "E": ["Emmm\r\n"], "V": [], "U": [], "L": [], "B": ["B2"], "K": ["King"], "F": [], "O": [], "W": [], "T": ["Test", "Test2"], "P": [], "Q": ["Queen"]]
var newDict = [String: [String]]()
for (key, value) in dict where !value.isEmpty {
    newDict[key] = value
}

Upvotes: 2

Related Questions