Dotdict
In the Python version you can alternatively be more explicit and usesomething like:
- 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
- initials = {}
- for name in ('peter', 'anders', 'bengt', 'bengtsson'):
- initial = name[0]
- # if initial not in initials:
- # initials[initial] = 0
- initials.setdefault(initial, 0)
- initials[initial] += 1
- print initials
- # outputs
- # {'a': 1, 'p': 1, 'b': 2}
Go
- package main
- import "fmt"
- func main() {
- names := []string{"peter", "anders", "bengt", "bengtsson"}
- initials := make(map[string]int)
- for _, name := range names {
- initial := string(name[0])
- initials[initial]++
- }
- fmt.Println(initials)
- // outputs
- // map[p:1 a:1 b:2]
- }