Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a declarative way to transform Array to Dictionary?

I want to get from this array of strings

let entries = ["x=5", "y=7", "z=10"] 

to this

let keyValuePairs = ["x" : "5", "y" : "7", "z" : "10"] 

I tried to use map but the problem seems to be that a key - value pair in a dictionary is not a distinct type, it's just in my mind, but not in the Dictionary type so I couldn't really provide a transform function because there is nothing to transform to. Plus map return an array so it's a no go.

Any ideas?

like image 898
Earl Grey Avatar asked Feb 21 '16 12:02

Earl Grey


People also ask

Is array a type of dictionary?

An array is just a sorted list of objects. A dictionary stores key-value pairs. There are no advantages or disadvantages, they are just two data structures, and you use the one you need.

What is faster dictionary or array Swift?

Generally speaking, Dictionaries provide constant, i.e. O(1), access, which means searching if a value exists and updating it are faster than with an Array , which, depending on implementation can be O(n). If those are things that you need to optimize for, then a Dictionary is a good choice.

What's the main difference between the array set and dictionary collection type?

Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Arrays are ordered collections of values. Sets are unordered collections of unique values. Dictionaries are unordered collections of key-value associations.

How to convert a dictionary to an array in Java?

Convert a Dictionary to an array – Use ToArray () method on the Values Property of the dictionary object Convert a Dictionary to a List – Use the ToList () method on the Values Property of the dictionary object Let us understand this with an example. The code is self-explained. Please go through the comments.

How to convert an array of dictionaries to a Dataframe 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. In this example, we created a dataframe by using the pandas library and then initialize a dictionary.

Why do we need to cast an array to a dictionary?

Because it makes accessing the object you really want easier. This data type is usually called a dictionary. One benefit of casting your arrays t o dictionaries is that you’ll never have to write methods to find objects by ID again. You will simply access them by their ID directly.

What is a dictionary data type?

This data type is usually called a dictionary. One benefit of casting your arrays t o dictionaries is that you’ll never have to write methods to find objects by ID again. You will simply access them by their ID directly.


1 Answers

Swift 4

As alluded to by fl034, this can be simplified some with Swift 4 where an error checked version looks like:

let foo = entries     .map { $0.components(separatedBy: "=") }     .reduce(into: [String:Int64]()) { dict, pair in         if pair.count == 2, let value = Int64(pair[1]) {             dict[pair[0]] = value         }     } 

Even simpler if you don't want the values as Ints:

let foo = entries     .map { $0.components(separatedBy: "=") }     .reduce(into: [String:String]()) { dict, pair in         if pair.count == 2 {             dict[pair[0]] = pair[1]         }     } 

Older TL;DR

Minus error checking, it looks pretty much like:

let foo = entries.map({ $0.componentsSeparatedByString("=") })     .reduce([String:Int]()) { acc, comps in         var ret = acc         ret[comps[0]] = Int(comps[1])         return ret     } 

Use map to turn the [String] into a split up [[String]] and then build the dictionary of [String:Int] from that using reduce.

Or, by adding an extension to Dictionary:

extension Dictionary {     init(elements:[(Key, Value)]) {         self.init()         for (key, value) in elements {             updateValue(value, forKey: key)         }     } } 

(Quite a useful extension btw, you can use it for a lot of map/filter operations on Dictionaries, really kind of a shame it doesn't exist by default)

It becomes even simpler:

let dict = Dictionary(elements: entries     .map({ $0.componentsSeparatedByString("=") })     .map({ ($0[0], Int($0[1])!)}) ) 

Of course, you can also combine the two map calls, but I prefer to break up the individual transforms.

If you want to add some error checking, flatMap can be used instead of map:

let dict2 = [String:Int](elements: entries     .map({ $0.componentsSeparatedByString("=") })     .flatMap({         if $0.count == 2, let value = Int($0[1]) {             return ($0[0], value)         } else {             return nil         }}) ) 

Again, if you want, you can obviously merge the map into the flatMap or split them for simplicity.

let dict2 = [String:Int](elements: entries.flatMap {     let parts = $0.componentsSeparatedByString("=")     if parts.count == 2, let value = Int(parts[1]) {         return (parts[0], value)     } else {         return nil     }} ) 
like image 51
David Berry Avatar answered Sep 19 '22 07:09

David Berry