To create a list of dictionaries in Kotlin, you can use the `mutableListOf` function to create an outer list and `mutableMapOf` function to create inner dictionaries, then add dictionaries as elements of the outer list.
In this example,
dict1
and dict2
using the mutableMapOf
function.listOfDicts
using the mutableListOf
function and initialize it with the inner dictionaries.fun main() {
val dict1 = mutableMapOf("key1" to "value1", "key2" to "value2")
val dict2 = mutableMapOf("key3" to "value3", "key4" to "value4")
val listOfDicts = mutableListOf(dict1, dict2)
println(listOfDicts)
}
[{key1=value1, key2=value2}, {key3=value3, key4=value4}]
In this example,
listOfDictsEmpty
using the mutableListOf
function.dict3
and dict4
using the mutableMapOf
function.add
method to add the inner dictionaries dict3
and dict4
to the outer list listOfDictsEmpty
.fun main() {
val listOfDictsEmpty = mutableListOf<MutableMap<String, String>>()
val dict3 = mutableMapOf<String, String>()
val dict4 = mutableMapOf<String, String>()
listOfDictsEmpty.add(dict3)
listOfDictsEmpty.add(dict4)
println(listOfDictsEmpty)
}
[{}, {}]
In this tutorial, we learned How to create a List of Dictionaries in Kotlin language with well detailed examples.