Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Analog of Python's setdefault in golang

Tags:

go

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.

like image 929
Evgeny Lazin Avatar asked Apr 20 '14 22:04

Evgeny Lazin


People also ask

What is Setdefault () method in Dictionary?

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.

What is the difference between GET and Setdefault in Python?

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.

How does Setdefault work in Python?

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 .

How do you create a map in go?

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.


2 Answers

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.

like image 75
Evan Avatar answered Sep 20 '22 07:09

Evan


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)
like image 2
OneOfOne Avatar answered Sep 20 '22 07:09

OneOfOne