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

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.

Related

appending key value pair to existing dictionary values in swift

I'm trying achieve below results. Where I can save multiple key values for multiple string items.
//dict["Setting1"] = ["key1":"val1"]
//dict["Setting1"] = ["key2":"val2"]
//dict["Setting2"] = ["key1":"val1"]
//dict["Setting2"] = ["key2":"val2"]
// and so on..
//or
//dict["Setting1"].append(["key2":"val2"]) // this doesn't work
//accessing dict["Settings1"]["key1"] ..should give me val1
var dict = [String:[String:String]]()
var lst1 = ["key2":"val2"]
dict["one"] = ["key1":"val1"]
dict["one"]?.append(lst1)
print(dict)
gives me error
error: value of type '[String : String]' has no member 'append'
obj["one"]?.append(lst1)
~~~~~~~~~~~ ^~~~~~
You're using a Dictionary which doesn't have methods like append(_:). append(:_) adds something to the end of an Array, but Dictionaries are unordered.
To add something to a Dictionary, you first define a key for it, and then assign it a value in the Dictionary
It'll look like this:
var dict = [String :[String: String]]()
var lst1 = ["key2": "val2"]
dict["one"] = ["key1": "val1"]
But you can't append to dict["one"], because it's not an array, you can only overwrite it
dict["one"] = lst1

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.

Swift dictionary, a key with multiple values

I would like to know how I can make a key of a dictionary have multiple values according to the data that comes to it.
Attached basic example:
var temp = [String: String] ()
temp ["dinningRoom"] = "Table"
temp ["dinningRoom"] = "Chair"
In this case, I always return "Chair", the last one I add, and I need to return all the items that I am adding on the same key.
In this case, the "dinningRoom" key should have two items that are "Table" and "Chair".
You can use Swift Tuples for such scenarios.
//Define you tuple with some name and attribute type
typealias MutipleValue = (firstObject: String, secondObject: String)
var dictionary = [String: MutipleValue]()
dictionary["diningRoom"] = MutipleValue(firstObject: "Chair", secondObject: "Table")
var value = dictionary["diningRoom"]
value?.firstObject
You can declare a dictionary whose value is an array and this can contain the data you want, for example:
var temp = [String: [String]]()
temp["dinningRoom"] = ["Table", "Chair", "Bottle"]
If you want to add a new element you can do it this way:
if temp["dinningRoom"] != nil {
temp["dinningRoom"]!.append("Flower")
} else {
temp["dinningRoom"] = ["Flower"]
}
Now temp["dinningRoom"] contains ["Table", "Chair", "Bottle", "Flower"]
Use Dictionary like this:
var temp = [String: Any]()
temp["dinningRoom"] = ["Table", "Chair"]
If you want to fetch all the elements from dinningRoom. You can use this:
let dinningRoomArray = temp["dinningRoom"] as? [String]
for room in dinningRoomArray{
print(room)
}
It is not compiled code but I mean to say that we can use Any as value instead of String or array of String. When you cast it from Any to [String]
using as? the app can handle the nil value.

Array from specific keys in a dictionaries array?

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"] }

How to sort dictionary by value?

My dictionary like this:
var items = [Int: [String]]()
var itemsResult = [Int: [String]]()
itmesResult stores the data downloaded from server.
and pass the data to items use of items = itmesResult
the value has 3 elements like ["Apple","/image/apple.png","29"]
and I want to sort the dictionary by first value which is Apple.
for (k,v) in (itemsResult.sorted(by: { $0.value[0] < $1.value[0] })) {
items[k] = v
}
The result of above code is not my expectation.
I would like to sort it alphabetically how can I do this?
Edit:
origin:
1:["Apple","/image/apple.png","29"]
2:["AAA","/image/aaa.png","29"]
3:["Banana","/image/banana.png","29"]
sorted:
2:["AAA","/image/aaa.png","29"]
1:["Apple","/image/apple.png","29"]
3:["Banana","/image/banana.png","29"]
I would like to sort it by first value.
So if I take your example, this does the trick:
var items = [Int: [String]]()
items[0] = ["Apple","/image/apple.png","29"]
items[1] = ["AAA","/image/aaa.png","29"]
items[2] = ["Banana","/image/banana.png","29"]
let itemResult = items.sorted { (first: (key: Int, value: [String]), second: (key: Int, value: [String])) -> Bool in
return first.value.first! < second.value.first!
}
print (itemResult)
The right thing to do is to use objects of course, and note that I'm not null checking the "first" object in each array, but this is not a problem to change.
Let me know if this is what you were looking for, the output is:
[(1, ["AAA", "/image/aaa.png", "29"]), (0, ["Apple", "/image/apple.png", "29"]), (2, ["Banana", "/image/banana.png", "29"])]
EDIT:
Also note, that this case doesn't actually "sort" the dictionary, because a dictionary is by definition not sorted, this creates an array of key-value objects sorted using the array indexes
Instead of saving these variable into an array of arrays, make them an array of dictionaries.
You can do this like so:
var dictionaries:[Dictionary<String, String>] = []
for item in items {
let dictionary = {"name": item[0], "url": item[1], "id" : item[2]}
dictionaries.append(dictionary)
}
You can get your sorted list of dictionaries like this:
dictionaries.sorted(by: { $0["name"] < $1["name"] })