Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert dictionary to array

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.

like image 693
Nick Avatar asked Aug 06 '15 01:08

Nick


People also ask

Can you put a dictionary in an array?

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.

How do you create an array of dictionaries in Python?

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.

Can a dictionary value be an array Python?

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.


2 Answers

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.

like image 54
vacawama Avatar answered Sep 27 '22 19:09

vacawama


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)") } 
like image 40
Ali Avatar answered Sep 27 '22 20:09

Ali