Dotdict

In the Python version you can alternatively be more explicit and usesomething like:

  1. initials.setdefault(initial, 0)

instead of first checking if the key is there.

Note that in Go, when you set the type to be an int it automaticallysets it to 0 upon initialization.

Python

  1. initials = {}
  2. for name in ('peter', 'anders', 'bengt', 'bengtsson'):
  3. initial = name[0]
  4. # if initial not in initials:
  5. # initials[initial] = 0
  6. initials.setdefault(initial, 0)
  7. initials[initial] += 1
  8. print initials
  9. # outputs
  10. # {'a': 1, 'p': 1, 'b': 2}

Go

  1. package main
  2.  
  3. import "fmt"
  4.  
  5. func main() {
  6. names := []string{"peter", "anders", "bengt", "bengtsson"}
  7. initials := make(map[string]int)
  8. for _, name := range names {
  9. initial := string(name[0])
  10. initials[initial]++
  11. }
  12. fmt.Println(initials)
  13. // outputs
  14. // map[p:1 a:1 b:2]
  15. }