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.
Python Dictionary setdefault() Method The setdefault() method returns the value of the item with the specified key. If the key does not exist, insert the key, with the specified value, see example below.
The get the method allows you to avoid getting a KeyError when the key doesn't exist however setdefault the method allows set default values when the key doesn't exist.
Python Dictionary setdefault() Method setdefault() method returns the value of the specified key in the dictionary. If the key is not found, then it adds the key with the specified defaultvalue. If the defaultvalue parameter is not specified, then it set None .
Go by Example: Maps Maps are Go's built-in associative data type (sometimes called hashes or dicts in other languages). To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With