In programming, using Python dictionary is one of the most common data structures, and its main function is to map keys to values. When using Golang, because it is a statically typed language, it does not support dictionary types like Python. Therefore, in some scenarios it is necessary to implement a data structure similar to a Python dictionary. This article will introduce how to implement Python dictionary in Golang.
1. Implementing Python dictionary
In Python, dictionaries are mainly implemented using hash tables. The hash table has a search efficiency of O(1). When operations such as insertion, deletion, and search are required, the hash table can be completed quickly. In Golang, a data structure similar to the dictionary in Python can be implemented through structures and maps.
By defining a structure that contains a data structure of key-value pairs, you can achieve a function similar to the dictionary in Python . Then, implement the corresponding methods, such as insertion, deletion, and search functions, to complete dictionary operations.
type Dict struct { items map[interface{}]interface{} } func NewDict() *Dict { return &Dict{items: map[interface{}]interface{}{}} } func (d *Dict) Set(key, value interface{}) { d.items[key] = value } func (d *Dict) Get(key interface{}) (interface{}, bool) { value, ok := d.items[key] return value, ok } func (d *Dict) Remove(key interface{}) { delete(d.items, key) } func (d *Dict) Contains(key interface{}) bool { _, ok := d.items[key] return ok } func (d *Dict) Len() int { return len(d.items) }
In the above code, the structure Dict defines a map of key-value pairs and implements the Set, Get, Remove, Contains and Len methods. Among them, the Set method is used to insert key-value pairs, the Get method is used to obtain the value according to the key, the Remove method is used to delete the key-value pair, the Contains method is used to determine whether a certain key is contained, and the Len method is used to obtain the length of the dictionary.
map is a built-in type in Golang, and its bottom layer is also implemented using a hash table. By using the map type, you can also achieve functions similar to dictionaries in Python.
type Dict map[interface{}]interface{} func NewDict() Dict { return make(map[interface{}]interface{}) } func (d Dict) Set(key, value interface{}) { d[key] = value } func (d Dict) Get(key interface{}) (interface{}, bool) { value, ok := d[key] return value, ok } func (d Dict) Remove(key interface{}) { delete(d, key) } func (d Dict) Contains(key interface{}) bool { _, ok := d[key] return ok } func (d Dict) Len() int { return len(d) }
In the above code, an alias Dict of type map[interface{}]interface{} is defined, and the Set, Get, Remove, Contains and Len methods are implemented in the structure. Among them, the Set method is used to insert key-value pairs, the Get method is used to obtain the value according to the key, the Remove method is used to delete the key-value pair, the Contains method is used to determine whether a certain key is contained, and the Len method is used to obtain the length of the dictionary.
2. Test code
Next, let’s write the test code to verify whether the implemented dictionary has the corresponding function.
func TestDict(t *testing.T) { // 基于结构体实现字典 d := NewDict() d.Set(1, "hello") d.Set("world", "golang") if v, ok := d.Get(1); !ok || v != "hello" { t.Errorf("expect: hello but get: %v", v) } if v, ok := d.Get("world"); !ok || v != "golang" { t.Errorf("expect: golang but get: %v", v) } d.Remove("world") if d.Contains("world") { t.Errorf("should not contain key: world") } if d.Len() != 1 { t.Errorf("expect length: 1 but get: %v", d.Len()) } // 基于map实现字典 dict := NewDict() dict.Set(1, "hello") dict.Set("world", "golang") if v, ok := dict.Get(1); !ok || v != "hello" { t.Errorf("expect: hello but get: %v", v) } if v, ok := dict.Get("world"); !ok || v != "golang" { t.Errorf("expect: golang but get: %v", v) } dict.Remove("world") if dict.Contains("world") { t.Errorf("should not contain key: world") } if dict.Len() != 1 { t.Errorf("expect length: 1 but get: %v", dict.Len()) } }
The test code contains two parts, corresponding to the dictionary based on the structure and map implementation. First, insert the key-value pair into the dictionary, then get the value and verify whether the value is correct. Then, delete a key-value pair and verify whether the dictionary length has changed.
3. Summary
Through the above examples, we can see that using structures and maps in Golang can achieve functions similar to dictionaries in Python. The implementation methods are mainly based on structure and based on map. No matter which implementation method is used, attention needs to be paid to issues such as hash conflicts to ensure its stability and efficiency. At the same time, we can also better understand their implementation principles and usage methods by implementing these basic data structures.
The above is the detailed content of golang implements python dictionary. For more information, please follow other related articles on the PHP Chinese website!