Convert the dataype of VALUES in Maps Go language - dictionary

I have a map in GO as :
var userinputmap = make(map[string]string)
and the values in it are of type :
[ABCD:30 EFGH:50 PORS:60]
Not that the 30,50,60 are strings over here.
I wish to have a same map but the numeric values should have float64 type instead of string type.
Desired output :
var output = make(map[string]float64)
I tried to do it but I get an error : cannot use <placeholder_name> (type string) as type float64 in assignment

You cannot do this by simple typecasting; the two maps have different representations in memory.
To solve this, you will have to iterate over every entry of the first map, convert the string representation of the float to a float64, then store the new value in the other map:
import "strconv"
var output = make(map[string]float64)
for key, value := range userinputmap {
if converted, err := strconv.ParseFloat(value, 64); err == nil {
output[key] = converted
}
}

Related

Converting between equivalent Go maps

I was looking for a way to convert a map to another map, without copying key by key. Both maps have the equivalent key type (as demonstrated below).
The code below seems to do the job, but I'm wondering what kind of pitfalls there might be if I use this?
package main
import (
"fmt"
"unsafe"
)
type A string
var (
x A = "x"
y A = "y"
)
func main() {
a := map[A]string{}
a[x] = "242342"
a[y] = "1234"
b := convert(a)
fmt.Println(a[x])
fmt.Println(b["x"])
fmt.Println(a[y])
fmt.Println(b["y"])
}
func convert(in map[A]string) map[string]string {
return *(*map[string]string)(unsafe.Pointer(&in))
}

First argument to append must be slice; have struct - golang map

Can't seem to use append for this case. Any help would be appreciated.
First argument to append must be slice:
package main
import (
"fmt"
)
type C struct {
value5 string
value6 string
}
type B struct {
value3 string
value4 C
}
type A struct {
value1 string
value2 B
}
type X struct{
key int
}
func main() {
letSee := map[X]A{}
letSee[X{1}]=A{"T",B{"T1",C{"T11","T12"}}}
letSee[X{1}]=append(letSee[X{1}], A{"L",B{"L1",C{"L11","L12"}}})
fmt.Println(letSee)
}
https://play.golang.org/p/R4gDO9MPBS
If in a map you want to store multiple values associated with the same key, the value type must be suitable for that. A struct isn't, but a slice is a perfect choice.
So change your value type to []A:
letSee := map[X][]A{}
letSee[X{1}] = []A{A{"T", B{"T1", C{"T11", "T12"}}}}
letSee[X{1}] = append(letSee[X{1}], A{"L", B{"L1", C{"L11", "L12"}}})
fmt.Printf("%+v", letSee)
Output (try it on the Go Playground):
map[{key:1}:[{value1:T value2:{value3:T1 value4:{value5:T11 value6:T12}}}
{value1:L value2:{value3:L1 value4:{value5:L11 value6:L12}}}]]

How efficiently to convert one dimensional array to two dimensional array in swift3

What is the efficient way to convert an array of pixelValues [UInt8] into two dimensional array of pixelValues rows - [[UInt8]]
You can write something like this:
var pixels: [UInt8] = [0,1,2,3, 4,5,6,7, 8,9,10,11, 12,13,14,15]
let bytesPerRow = 4
assert(pixels.count % bytesPerRow == 0)
let pixels2d: [[UInt8]] = stride(from: 0, to: pixels.count, by: bytesPerRow).map {
Array(pixels[$0..<$0+bytesPerRow])
}
But with the value semantics of Swift Arrays, all attempt to create new nested Array requires copying the content, so may not be "efficient" enough for your purpose.
Re-consider if you really need such nested Array.
This should work
private func convert1Dto2DArray(oneDArray:[String], stringsPerRow:Int)->[[String]]?{
var target = oneDArray
var outOfIndexArray:[String] = [String]()
let reminder = oneDArray.count % stringsPerRow
if reminder > 0 && reminder <= stringsPerRow{
let suffix = oneDArray.suffix(reminder)
let list = oneDArray.prefix(oneDArray.count - reminder)
target = Array(list)
outOfIndexArray = Array(suffix)
}
var array2D: [[String]] = stride(from: 0, to: target.count, by: stringsPerRow).map {
Array(target[$0..<$0+stringsPerRow])}
if !outOfIndexArray.isEmpty{
array2D.append(outOfIndexArray)
}
return array2D
}

How to convert List to Map in Kotlin?

For example I have a list of strings like:
val list = listOf("a", "b", "c", "d")
and I want to convert it to a map, where the strings are the keys.
I know I should use the .toMap() function, but I don't know how, and I haven't seen any examples of it.
You have two choices:
The first and most performant is to use associateBy function that takes two lambdas for generating the key and value, and inlines the creation of the map:
val map = friends.associateBy({it.facebookId}, {it.points})
The second, less performant, is to use the standard map function to create a list of Pair which can be used by toMap to generate the final map:
val map = friends.map { it.facebookId to it.points }.toMap()
From List to Map with associate function
With Kotlin 1.3, List has a function called associate. associate has the following declaration:
fun <T, K, V> Iterable<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V>
Returns a Map containing key-value pairs provided by transform function applied to elements of the given collection.
Usage:
class Person(val name: String, val id: Int)
fun main() {
val friends = listOf(Person("Sue Helen", 1), Person("JR", 2), Person("Pamela", 3))
val map = friends.associate({ Pair(it.id, it.name) })
//val map = friends.associate({ it.id to it.name }) // also works
println(map) // prints: {1=Sue Helen, 2=JR, 3=Pamela}
}
From List to Map with associateBy function
With Kotlin, List has a function called associateBy. associateBy has the following declaration:
fun <T, K, V> Iterable<T>.associateBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, V>
Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given collection.
Usage:
class Person(val name: String, val id: Int)
fun main() {
val friends = listOf(Person("Sue Helen", 1), Person("JR", 2), Person("Pamela", 3))
val map = friends.associateBy(keySelector = { person -> person.id }, valueTransform = { person -> person.name })
//val map = friends.associateBy({ it.id }, { it.name }) // also works
println(map) // prints: {1=Sue Helen, 2=JR, 3=Pamela}
}
If you have duplicates in your list that you don't want to lose, you can do this using groupBy.
Otherwise, like everyone else said, use associate/By/With (which in the case of duplicates, I believe, will only return the last value with that key).
An example grouping a list of people by age:
class Person(val name: String, val age: Int)
fun main() {
val people = listOf(Person("Sue Helen", 31), Person("JR", 25), Person("Pamela", 31))
val duplicatesKept = people.groupBy { it.age }
val duplicatesLost = people.associateBy({ it.age }, { it })
println(duplicatesKept)
println(duplicatesLost)
}
Results:
{31=[Person#41629346, Person#4eec7777], 25=[Person#3b07d329]}
{31=Person#4eec7777, 25=Person#3b07d329}
Convert a Iteratable Sequence Elements to a Map in kotlin ,
associate vs associateBy vs associateWith:
*Reference:Kotlin Documentation
1- associate (to set both Keys & Values): Build a map that can set key & value elements :
IterableSequenceElements.associate { newKey to newValue } //Output => Map {newKey : newValue ,...}
If any of two pairs would have the same key the last one gets added to the map.
The returned map preserves the entry iteration order of the original array.
2- associateBy (just set Keys by calculation): Build a map that we can set new Keys, analogous elements will be set for values
IterableSequenceElements.associateBy { newKey } //Result: => Map {newKey : 'Values will be set from analogous IterableSequenceElements' ,...}
3- associateWith (just set Values by calculation): Build a map that we can set new Values, analogous elements will be set for Keys
IterableSequenceElements.associateWith { newValue } //Result => Map { 'Keys will be set from analogous IterableSequenceElements' : newValue , ...}
Example from Kotlin tips :
You can use associate for this task:
val list = listOf("a", "b", "c", "d")
val m: Map<String, Int> = list.associate { it to it.length }
In this example, the strings from list become the keys and their corresponding lengths (as an example) become the values inside the map.
That have changed on the RC version.
I am using val map = list.groupByTo(destinationMap, {it.facebookId}, { it -> it.point })

Convert map[interface {}]interface {} to map[string]string

From a source I cannot influence I am given data in a map, which arrives as map[interface {}]interface {}.
I need to process the contained data, preferably as map[string]string (the data within is perfectly suitable for that).
I need to generate a list of the keys from the data as well, as those are not known beforehand.
Most similar questions I could find on the web say more or less, that this is impossible, but if my map is m, fmt.Println(m) shows the data is there, readable as map[k0:v0 K1:v1 k2:v2 ... ].
How can I do what fmt.Println is able to do?
A secure way to process unknown interfaces, just use fmt.Sprintf()
https://play.golang.org/p/gOiyD4KpQGz
package main
import (
"fmt"
)
func main() {
mapInterface := make(map[interface{}]interface{})
mapString := make(map[string]string)
mapInterface["k1"] = 1
mapInterface[3] = "hello"
mapInterface["world"] = 1.05
for key, value := range mapInterface {
strKey := fmt.Sprintf("%v", key)
strValue := fmt.Sprintf("%v", value)
mapString[strKey] = strValue
}
fmt.Printf("%#v", mapString)
}
Perhaps I misunderstand the question, but would this work?
m := make(map[interface{}]interface{})
m["foo"] = "bar"
m2 := make(map[string]string)
for key, value := range m {
switch key := key.(type) {
case string:
switch value := value.(type) {
case string:
m2[key] = value
}
}
}
// data is map[string]interface{}
form := make(map[string]string)
for k, v := range data {
form[k] = v.(string)
}

Resources