Golang Program to Iterate through Elements of Dictionary


In Golang, a dictionary is like a map which is a group of key-value pairs with a unique key for each value. The values can be of any type, and the keys can be of any type that is similar, such as strings or integers. We can build an empty map by using the built-in "make" function, and then add, retrieve, or update values. We will use two examples here to iterate through elements of a dictionary where in the first example loop will be used to iterate through the elements whereas in the next example slices will be used to iterate through the elements

Method 1: Using for loop and range keyword

This method creates a dictionary dict_value with three key-value pairs and then iterates through the dictionary's components using a for loop and the range keyword. The current element's key and value are allocated to the appropriate variables during each iteration of the loop, and then they are reported to the console.

Syntax

map[strings]

A map implements an unordered collection of key-value pairs. A map's keys are all distinct and are used to get the values they correspond to. They are declared using the keyword "map" followed by the key type in square brackets and the value type and can be produced using the built-in "make" function. The square bracket syntax can be used to add, retrieve, or update the key-value pairs. A dynamic map's size can increase or decrease as necessary. In Go programming, maps are a typical data structure that is useful for illustrating relationships between keys and values.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Create a main function and in that function make a dictionary named dict_values using map function that contains key-value pairs.

  • Step 3 − Use the range keyword as the initial value of a for loop to iterate through the dictionary's items.

  • Step 4 − The key and value of the current element are allocated to the associated variables throughout each iteration of the loop.

  • Step 5 − The current element's key and value will be printed to the console using fmt.Println() function where ln means new line.

  • Step 6 − Till every element in the dictionary has been processed, repeat steps 3 and 4 for each element.

Example

In this example we will use a loop and range keyword along with it to iterate through elements of dictionary. Let’s see how its code is executed.

package main
import "fmt"

func main() {
   // Define a dictionary
   dict_values := map[string]int{
      "Apple":   100,
      "Mangoes": 200,
      "Banana":  60,
   }
   fmt.Println("The dictionary is iterated as follows:")
   
   // Iterate through the elements of the dictionary
   for key, value := range dict_values {
      fmt.Println(key, value)
   }
}

Output

The dictionary is iterated as follows:
Apple 100
Mangoes 200
Banana 60

Method 2: Using Slices

In this method, we first use a for loop and the range keyword to slice up the dictionary's keys. Then, using an additional for loop and the index operator [], we cycle through the keys to obtain the appropriate values. Finally, we report each element's key and value to the console.

Syntax

func append(slice, element_1, element_2…, element_N) []T

The append function is used to add values to an array slice. It takes number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of array containing all the values.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package) package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Create a function main and in that function create a make a dictionary dict_values using map function that contains key-value pairs.

  • Step 3 − To iterate through the dictionary's keys and produce a slice of the keys, initialize a for loop with the range keyword.

  • Step 4 − Set up a second for loop and begin iterating through the keys in the newly formed slice.

  • Step 5 − Utilize the index operator [] to retrieve the relevant value from the dictionary for each key in the slice.

  • Step 6 − Each element's key and value will be printed to the console using fmt.Println() function where ln means new line.

  • Step 7 − For each key in the slice, repeat steps 4 and 5 until all components have been processed.

Example

In this example slices are used to iterate through elements of a dictionary. Let’s see through the code.

package main
import "fmt"

func main() {
   // Define a dictionary
   dict_values := map[string]int{
      "Apple":   100,
      "Mangoes": 200,
      "Banana":  60,
   }

   // Get a slice of the keys from the dictionary
   slice := make([]string, 0, len(dict_values))
   for key := range dict_values {
      slice = append(slice, key)
   }
   fmt.Println("The dictionary is iterated as follows:")
   // Iterate through the keys and get the corresponding values
   for _, key := range slice {
      value := dict_values[key]
      fmt.Println(key, value)
   }
}

Output

The dictionary is iterated as follows:
Apple 100
Mangoes 200
Banana 60

Conclusion

We executed the program of iterating through the elements of dictionary using two methods. In the first method we used a for loop and range keyword and in the second example we used slices to iterate through elements of a dictionary.

Updated on: 22-Feb-2023

968 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements