Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Convert Array to Dictionary

I just want convert an array of Player Names into a dictionary Scoreboard, giving everyone an initial score of 0.

Meaning...

var playerNames = ["Harry", "Ron", "Hermione"]

becomes...

var scoreBoard: [String:Int] = [ "Ron":0, "Harry":0, "Hermione":0 ]

This is my first time asking a question, but I’m totally completely stuck on what feels so simple and all how-to's/questions I've found are off in some way. I have tried using reduce in a variety of ways, but always end up short. Thanks in advance!

like image 841
bbwerner Avatar asked Jun 12 '18 17:06

bbwerner


People also ask

How do you convert an array to a dictionary?

To convert a numpy array to dictionary the following program uses dict(enumerate(array. flatten(), 1)) and this is what it exactly does: array. flatten: This function is used to get a copy of given array, collapsed into one dimension.

What is reduce in Swift?

reduce(_:_:) Returns the result of combining the elements of the sequence using the given closure.


2 Answers

Here's a quick one liner that I like to use:

let scoreboard = playerNames.reduce(into: [String: Int]()) { $0[$1] = 0 }
like image 60
jmad8 Avatar answered Oct 24 '22 03:10

jmad8


If the player names are known to be all different then you can do

let playerNames = ["Harry", "Ron", "Hermione", "Ron"]

var scoreBoard = Dictionary(uniqueKeysWithValues: zip(playerNames,
                                                      repeatElement(0, count: playerNames.count)))

print(scoreBoard) // ["Harry": 0, "Ron": 0, "Hermione": 0]

Here zip is used to create a sequence of player/score pairs, from which the dictionary is created.

Remark: Originally I had used AnySequence { 0 } to generate the zeros. Using repeatElement() instead was suggested by Alexander and has the advantage that the correct required capacity is passed to the dictionary intializer.

like image 39
Martin R Avatar answered Oct 24 '22 03:10

Martin R