I want to convert my dictionary to an array, by showing each [String : Int]
of the dictionary as a string in the array.
For example:
var myDict: [String : Int] = ["attack" : 1, "defend" : 5, "block" : 12]
I'm aware of myDict.keys.array
and myDict.values.array
, but I want them to show up in an array together. Here's what I mean:
var myDictConvertedToArray = ["attack 1", "defend 5", "block 12"]
Thanks in advance.
You cannot use string indexes in arrays, but you can apply a Dictionary object in its place, and use string keys to access the dictionary items. The dictionary object has the following benefits when compared with arrays: The size of the Dictionary object can be set dynamically.
In Python to convert an array of dictionaries to a dataframe, we can easily use the function dict. items(). By using dict. items() to get a set like a dictionary with the key-value pairs.
A dictionary is sometimes called an associative array because it associates a key with an item. The keys behave in a way similar to indices in an array, except that array indices are numeric and keys are arbitrary strings. Each key in a single Dictionary object must be unique.
You can use a for loop to iterate through the dictionary key/value pairs to construct your array:
var myDict: [String : Int] = ["attack" : 1, "defend" : 5, "block" : 12] var arr = [String]() for (key, value) in myDict { arr.append("\(key) \(value)") }
Note: Dictionaries are unordered, so the order of your array might not be what you expect.
In Swift 2 and later, this also can be done with map
:
let arr = myDict.map { "\($0) \($1)" }
This can also be written as:
let arr = myDict.map { "\($0.key) \($0.value)" }
which is clearer if not as short.
The general case for creating an array out of ONLY VALUES of a dictionary in Swift 3 is (I assume it also works in older versions of swift):
let arrayFromDic = Array(dic.values.map{ $0 })
Example:
let dic = ["1":"a", "2":"b","3":"c"] let ps = Array(dic.values.map{ $0 }) print("\(ps)") for p in ps { print("\(p)") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With