Array from Dictionary Keys in Swift

Array from dictionary keys in swift

Swift 3 & Swift 4

componentArray = Array(dict.keys) // for Dictionary

componentArray = dict.allKeys // for NSDictionary

Dictionary fetch all keys and use them as Array

Maybe using map will help:

let dictionary: [String:String] = [:]
let keys: [String] = dictionary.map({ $0.key })

Don't like map? Go this way:

let dictionary: [String:String] = [:]
let keys: Array = Array(dictionary.keys)

How do I convert data dictionary into an array Swift?

About using map, I guess this page is helpful and visual.

let names = data.map { return $0.key }
print(names) // prints ["café-veritas", "cafe-myriade"]

Appending dictionary values to array in Swift

You should only sort the keys and then use that array to select from the dictionary and append your sortedValues array. I made the sortedKeys into a local variable

func sortItems() {
let sortedKeys = self.dictionary.keys.sorted(by: >)

for key in sortedKeys {
if let obj = dictionary[key] {
self.sortedValues.append(obj)
}
}
}

I don't know if this will make a difference in regard to the crash but another way is to let the function return an array

func sortItems() -> [Object] {
let sortedKeys = self.dictionary.keys.sorted(by: >)
var result: [Object]()

for key in sortedKeys {
if let obj = dictionary[key] {
result.append(obj)
}
}
return result
}

and then call it

self.sortedValues = sortItems()

How do I get the key at a specific index from a Dictionary in Swift?

That's because keys returns LazyMapCollection<[Key : Value], Key>, which can't be subscripted with an Int. One way to handle this is to advance the dictionary's startIndex by the integer that you wanted to subscript by, for example:

let intIndex = 1 // where intIndex < myDictionary.count
let index = myDictionary.index(myDictionary.startIndex, offsetBy: intIndex)
myDictionary.keys[index]

Another possible solution would be to initialize an array with keys as input, then you can use integer subscripts on the result:

let firstKey = Array(myDictionary.keys)[0] // or .first

Remember, dictionaries are inherently unordered, so don't expect the key at a given index to always be the same.

Sort dictionary by keys in Swift

Dictionary already has a sorted method that takes a closure that defines the sorting function. You can sort by keys in the closure, then simply map over the resulting tuples to get the values only.

let sortedDictKeys = dict.sorted(by: { $0.key < $1.key }).map(\.value)

Getting elements from array of dictionary and save the keys as string, and values as string

A dictionary has a keys and a values property which return the
keys/values as a (lazy) collection. For the values you just have
to join them:

let dict = [14: "2", 17: "5", 6: "5", 12: "Ali", 11: "0", 2: "4", 5: "It it it", 15: "5", 18: "2", 16: "5", 8: "2", 13: "4", 19: "4", 1: "2", 4: "12-09-2017 - 9:52"]

let values = dict.values.joined(separator: ",")
// Ali,5,2,It it it,5,0,4,5,4,4,2,12-09-2017 - 9:52,5,2,2

The keys are integers and must be converted to strings first:

let keys = dict.keys.map(String.init).joined(separator: ",")
// 12,17,14,5,15,11,13,16,19,2,18,4,6,8,1

The order is unspecified, but the same for keys and values.

How to sort Dictionary by keys where values are array of objects in Swift 4?

struct Name: CustomStringConvertible {
let id: Int
let name: String
let native: String
let meaning: String
let origin: String
let isFavorite: Bool
let gender: String
var description: String {
return "Id: " + String(id) + " - Name: " + name
}
}

let name1 = Name(id: 1, name: "Tim Cook", native: "native", meaning: "meaning", origin: "origin", isFavorite: true, gender: "Male")
let name2 = Name(id: 2, name: "Steve Jobs", native: "native", meaning: "meaning", origin: "origin", isFavorite: true, gender: "Male")
let name3 = Name(id: 3, name: "Tiger Woods", native: "native", meaning: "meaning", origin: "origin", isFavorite: true, gender: "Male")
let name4 = Name(id: 4, name: "Socrates", native: "native", meaning: "meaning", origin: "origin", isFavorite: true, gender: "Male")

let names = [name1, name2, name3, name4]


let dictionary = names.sorted(by: {$0.name < $1.name }).reduce(into: [String: [Name]]()) { result, element in
// make sure there is at least one letter in your string else return
guard let first = element.name.first else { return }
// create a string with that initial
let initial = String(first)
// initialize an array with one element or add another element to the existing value
result[initial, default: []].append(element)
}

let sorted = dictionary.sorted {$0.key < $1.key}
print(sorted) // "[(key: "S", value: [Id: 4 - Name: Socrates, Id: 2 - Name: Steve Jobs]), (key: "T", value: [Id: 3 - Name: Tiger Woods, Id: 1 - Name: Tim Cook])]\n"

Storing and accessing object array in dictionary - Swift 3 - macOS

If you want to store to store all players under same key then first collect all players and then add it to the corresponding key.

let suppose you read player from csv. I am writing pseudo code.

   // For playerData in readPlayerFormCSV()
// Now you will create a Player Object using data
// player = Player(playerData)

// One you have the player object
// create the dictionary where you want to store them
var dict: [String: Array] = [:]

// Check which team the player belongs
// if player belongs to LAK then add it player array with team key.

dict["LAK"].append(player)

My question is how do I get it to store all of the players under the same key?

If you just want players under a single key, Just add it to the corresponding array. I would not recommend this because the purpose of Dictionary is to store "Key-Value" pairs and adding just a single key doesn't make sense. It better to use an array.

  dict["Your Key"].append(player)


Related Topics



Leave a reply



Submit