Evgeny Lazin
Evgeny Lazin

Reputation: 9413

Analog of Python's setdefault in golang

There is handy shortcut for dictionaries in python - setdefault method. For example, if I have dict that represents mapping from string to list, I can write something like this

if key not in map:
    map[key] = []
map[key].append(value)

this is too verbose and more pythonic way to do this is like so:

map.setdefault(key, []).append(value)

there is a defaultdict class, by the way.

So my question is - is there something similar for maps in Go? I'm really annoyed working with types like map[string][]int and similar.

Upvotes: 10

Views: 4450

Answers (2)

OneOfOne
OneOfOne

Reputation: 99274

It works fine with the default map, play :

m := make(map[string][]int)
m["test0"] = append(m["test0"], 10)
m["test1"] = append(m["test1"], 10)
m["test2"] = append(m["test2"], 10)

Upvotes: 2

Evan
Evan

Reputation: 6545

There isn't such a thing specifically for maps, but nil is a valid empty slice (which can be used with the append builtin) so the following code:

x := make(map[string][]int)
key := "foo"
x[key] = append(x[key], 1)

Will work regardless of whether key exists in the map or not.

Upvotes: 13

Related Questions