Array from specific keys in a dictionaries array? - swift

I have an array of dictionaries : [[String:String]]
From every dictionary in this array I want only the key "name" to be added into a new array.
I can loop over them obviously, but is there a way with 1 line (similar to array.keys only with specific keys) ?

You can use map for that.
let nameArray = yourArray.map { $0["name"]! }
If all the dictionaries from array not contains name key then use flatMap.
let nameArray = yourArray.flatMap { $0["name"] }

Related

Getting Array value in a dictionary swift

I am trying to get key and value in a Dictionary while I am able to the key and map it to a dictionary, I am unable to get the value which is an array.
var dict = [String: [String]]
I was able to get the key as an array which is what I want like:
var keyArray = self.dict.map { $0.key }
How can I get the value which is already an array
Use flatMap if you want to flatten the result you get when you use map which is of type [[String]].
let valueArray = dict.flatMap { $0.value } // gives `[String]` mapping all the values
Here is how you get each string count Array
var dict = [String: [String]]()
let countOfEachString = dict.map { $0.value }.map{ $0.count }
Each value is a string array .. so to access each array you need to use map again

Add two dictionary values in new array . the array values will remains unchanged from its position

Add two dictionary values in a new array. the array values will remain unchanged from its position. I need to add two dictionary values in a new array. The values added in the array must remain constant at every run.
var dictionary1:[String:Int] = ["Mohan":75, "Raghu":82, "John":79]
var dictionary2:[String:Int] = ["Surya":91, "John":79, "Saranya":92]
dictionary1.merge(dictionary2){(current, _) in current}
var arr : [String] = []
for (key, value) in dictionary1 { arr.append("(key) (value)") }
print(dictionary1)
Simply use append(contentsOf:) to add the contents of dictionary1 and dictionary2 to arr. Use map(_:) to format the key-value pairs while adding to the array.
let dictionary1 = ["Mohan":75, "Raghu":82, "John":79]
let dictionary2 = ["Surya":91, "John":79, "Saranya":92]
var arr = [String]()
arr.append(contentsOf: dictionary1.map({"\($0.key) \($0.value)"}))
arr.append(contentsOf: dictionary2.map({"\($0.key) \($0.value)"}))
print(arr) //["Mohan 75", "John 79", "Raghu 82", "Surya 91", "John 79", "Saranya 92"]
As apple stats, you can use KeyValuePairs to maintain ordered collection of key-value pairs and don’t require the fast key lookup that the Dictionary type provides.
let recordTimes: KeyValuePairs = ["Florence Griffith-Joyner": 10.49,
"Evelyn Ashford": 10.76,
"Evelyn Ashford": 10.79,
"Marlies Gohr": 10.81]
print(recordTimes.first!)
// Prints "("Florence Griffith-Joyner", 10.49)"
Check if it is helpful in your case.

Getting values out of dictionaries which have arrays as values

I have a dictionary which contains languages as values and the initial character of every language name (A, B, C, ...) as for the key.
var dictionary = [Character: [Language]]()
I would like to get all the languages out of the dictionary in the form of an array. To do so, I do
let languages = dictionary.values // Dictionary<Character, [Language]>.Values
That's not an array. I try to get the array like this
let languages = Array(tableViewSource.values) // [[Language]]
This returns an array of an array. How do I just get an array of languages? I saw the merge(_:uniquingKeysWith:) but I don't need to merge dictionaries.
You can try
let allLangs = nestedArr.reduce([], +)
Martin R's and Sh_Khan's answers outline the standard ways of doing this (you basically just want to flatten an array). However I'd like to show a more "manual" approach:
var langs = [String]()
for lang_list in dictionary.values {
langs.append(contentsOf: lang_list)
}
Alternatively, you can use the += operator instead of .append(contentsOf:). An easier way of doing this would be using flatMap(_:):
dictionary.values.flatMap { $0 }
If you want a single array (concatenating all dictionary values) then
Array(dictionary.values.joined())
does the trick. (This creates the final array without creating any additional intermediate arrays.)
Example:
let dictionary: [Character: [String]] = ["E": ["espanol", "english"], "G": ["german", "greek"]]
let langs = Array(dictionary.values.joined())
print(langs) // ["german", "greek", "espanol", "english"]
Note that the order of key/value pairs in a dictionary is unspecified.
An alternative is
let dictionary: [Character: [String]] = ["E": ["espanol", "english"], "G": ["german", "greek"]]
let langs = dictionary.keys.sorted().flatMap { dictionary[$0]! }
print(langs) // ["espanol", "english", "german", "greek"]
which gives the languages sorted by the corresponding keys.

Get element from array of dictionaries according to key

I have array like [[:String:Any]]
I have a value string , and i want to extract the element with that key without looping (one line).
To check if its there I used this :
if(array.map{$0["NAME"] as! String}.contains(value)){
Is there a way to also extract this dictionary within this if statement ?
For that no need to map the array. You can use contains(where:)
if array.contains(where: { $0["name"] as? String == value }) {
print("Exist")
}
If you want object(dictionary) from array also than you can use first(where:)
if let dict = array.first(where: { $0["name"] as? String == value }) {
print(dict)
}
For more on first(where:) check this SO Thread

get Values from NSMutableDictionary in swift?

I have a stored NSMutableDictionary in NSUSerDefaluts and i have retrieve that successfully.
if var tempFeed: NSDictionary = NSUserDefaults.standardUserDefaults().dictionaryForKey("selectedFeeds") {
println("selected Feed: \(tempFeed)")
savedDictionary = tempFeed.mutableCopy() as NSMutableDictionary
The Question is How can i convert that MutableDictionary into an array/MuatableArray and iterate it so i can get the values of it.Here is the Dictionary. i want to get the values for all URL in that.
{
4 = {
URL = "myurl1";
};
5 = {
URL = "myurl3";
};
6 = {
URL = "myurl3";
};
}
I have tried number of options with failure.
Thank you.
If you want to add all the urls into an array, iterate over it and add append all values to some array.
for (_,urlDict) in savedDictionary {
for(_,url) in urlDict {
urlArr.append(url) // create empty urlArr before
}
}
urlArr now contains all the urls (not ordered)
You can use .values.array on your dictionary to get the values unordered.
as an array
Then, you can just add your NSArray to your NSMutableArray.
var mutableArray:NSMutableArray = NSMutableArray(array: savedDictionary .values.array)
If all you want to do is iterate over it, you don’t have to convert it to an array. You can do that directly:
for (key,value) in savedDictionary {
println("\(key) = \(value)")
}
(if you’re not interested in the key at all, you can replace that variable name with _ to ignore it).
Alternatively, instead of making tempFeed of type NSDictionary, just leave it as the type dictionaryForKey returns, which is a Swift dictionary. This has a .values property, which is a lazy sequence of all the values in the dictionary. You can convert that to an array (so tempFeed.values.array) or perform operations on it directly (use it in for…in, map it such as tempFeeds.values.map { NSURL(string: toString($0)) } etc.)