0

I'm trying to normalize a structure from a CSV file, which is like this:

name, note
'Joe', 5
'Joe', 3
'Ashley', 1
'Ashley', 7
'Ashley', 4

to a map, that after read that file, will be reduced to:

map [string][]string{
    "joe" = {5, 3},
    "ashley" = {1, 7, 4},
}

what's the best approach to do that?

Im new in Go, and the code I created is something like this:

func main() {
    fileName := "new"
    xlsx, err := excelize.OpenFile(fileName + ".xlsx")
    if err != nil {
        fmt.Println(err)
        return
    }
    rows, err := xlsx.Rows("Sheet1")
    if err != nil {
        fmt.Print(err)
    }

    for rows.Next() {

        column, err := rows.Columns()
        if err != nil {
            println(err)

        }

        for i := 0; i < 1; i++ {
            if i == i {
                m := map[string][]string{
                    column[i]: []string{column[1]},
                }
                fmt.Printf("%v\n", m)
            }

        }
    }
}
4
  • 1
    What is your question? Commented Dec 6, 2022 at 18:32
  • @Adrian I don't know how to return a map with 1 key and multiple values. I did return a map with 1 key and 1 value and return the next map with the same key and next value. Commented Dec 6, 2022 at 18:58
  • Your code doesn't return anything, can you clarify your question? Commented Dec 6, 2022 at 19:03
  • @Adrian I reformulated the question. Commented Dec 6, 2022 at 19:28

1 Answer 1

1

It should be pretty straightforward:

m := map[string][]string{}
for rows.Next() {
    column, err := rows.Columns()
    if err != nil {
        panic(err)
    }
    if len(column) < 2 {
        panic("row too short")
    }
    m[column[0]] = append(m[column[0]], column[1])
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.