Add entries to a Dict, look up a value by key, and iterate over all entries.

← Collections and Data Structures · Ref: Q1161

Dict operations use DictEntry, getOrDefault, and for-in:

  codes <- Dict() of (String, String)
  codes += DictEntry("GB", "United Kingdom")
  result <- codes.getOrDefault("GB", "Unknown")
  for entry in codes
    stdout.println($entry)

Dict type uses (K, V) parentheses. getOrDefault returns the value or a fallback.

See Q1158 for Dict iteration. See Q1095 for custom Dict keys.

Example

defines module qa.collections.dictcomprehensive

  defines program

    DictComprehensiveDemo()
      stdout <- Stdout()

      codes <- Dict() of (String, String)
      codes += DictEntry("GB", "United Kingdom")
      codes += DictEntry("US", "United States")
      codes += DictEntry("DE", "Germany")

      //Lookup by key
      result <- codes.getOrDefault("GB", "Unknown")
      stdout.println(`GB: ${result}`)

      //Missing key — returns default
      missing <- codes.getOrDefault("FR", "Not found")
      stdout.println(`FR: ${missing}`)

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

Common mistakes

E01010 — Dict type parameters must be in parentheses: Dict() of (K, V).

Incorrect:

      codes <- Dict() of String, String

Correct:

      codes <- Dict() of (String, String)
Other ways to ask this
  • I need to build a dictionary, retrieve values, and loop through entries
  • In Python I'd use dict[key] = value and for k,v in dict.items(). Write the EK9 Dict
  • Given a Dict of country codes to names, add entries, look up, and iterate
  • Show the core Dict operations: add with DictEntry, getOrDefault, and for-in

Coming from another language?

Python: dict[key] = value, dict.get(key, default). Java: map.put(), map.getOrDefault(). EK9: += DictEntry(), getOrDefault().

Keywords: iterate, lookup, getOrDefault, Dict, add, DictEntry