Create a Dict with a curly-brace {key: value} literal, then add entries using DictEntry.

← Collections and Data Structures · Ref: Q1179

EK9 has a dict literal: curly braces around key: value pairs. The key and value types are inferred:

  settings <- {"theme": "dark", "lang": "en"}    // Dict of (String, String)

To add entries later, use DictEntry(key, value) with +=:

  settings += DictEntry("fontSize", "14")

The entry must match the Dict's types: DictEntry("fontSize", 14) is a DictEntry of (String, Integer), so adding it to a Dict of (String, String) is E50060 (method not resolved).

To start with an empty Dict, give the types explicitly: settings <- Dict() of (String, String).

See Q1178 for Dict creation. See Q1161 for full Dict operations.

Example

defines module qa.collections.dictnoliteralsyntax

  defines program

    DictNoLiteralSyntaxDemo()
      stdout <- Stdout()

      //A dict literal: the types are inferred as Dict of (String, String)
      settings <- {"theme": "dark", "lang": "en"}

      //Add more entries with DictEntry
      settings += DictEntry("fontSize", "14")

      //Retrieve values
      theme <- settings.getOrDefault("theme", "light")
      stdout.println(`Theme: ${theme}`)

      lang <- settings.getOrDefault("lang", "en")
      stdout.println(`Language: ${lang}`)

      //Iterate
      for entry in settings
        stdout.println($entry)

Common mistakes

E50060 — The literal made settings a Dict of (String, String), so every DictEntry added must be (String, String). DictEntry("fontSize", 14) is (String, Integer) and no += accepts it. See ek9 -h E50060 for details.

Incorrect:

      settings += DictEntry("fontSize", 14)

Correct:

      settings += DictEntry("fontSize", "14")
Other ways to ask this
  • Write code showing how to create an EK9 dict with a {key: value} literal
  • How do I initialise a dict with curly braces in EK9?
  • In JavaScript I'd use {name: 'Alice', age: 30}. What is the EK9 Dict equivalent?
  • Build a settings Dict with a literal and then add more entries with DictEntry

Coming from another language?

JavaScript: {key: value}. Python: {key: value}. Java: Map.of(k, v). Go: map[string]string{k: v}. EK9: {k: v, k2: v2} literal (types inferred, e.g. Dict of (String, String)); add entries later with += DictEntry(k, v), or start empty with Dict() of (K, V).

Keywords: syntax, curly brace, dict literal, literal, DictEntry, Dict