Create a Dict, add entries with DictEntry, and look up values with getOrDefault.

← Collections and Data Structures · Ref: Q1178

Use Dict() of (K, V) with DictEntry and getOrDefault:

  prices <- Dict() of (String, Float)
  prices += DictEntry("Widget", 9.99)
  result <- prices.getOrDefault("Widget", 0.0)

Dict uses parenthesised type parameters. Add entries with DictEntry(key, value). Retrieve with getOrDefault(key, fallback) — there is no .get() method.

See Q1161 for comprehensive Dict. See Q1158 for Dict iteration. See Q129 for missing keys.

Example

defines module qa.collections.dictcorrectsyntax

  defines program

    DictCorrectSyntaxDemo()
      stdout <- Stdout()

      //Create a Dict with parenthesised type parameters
      prices <- Dict() of (String, Float)

      //Add entries using DictEntry(key, value)
      prices += DictEntry("Widget", 9.99)
      prices += DictEntry("Gadget", 24.50)
      prices += DictEntry("Gizmo", 4.99)

      //Look up existing key — returns the value
      widgetPrice <- prices.getOrDefault("Widget", 0.0)
      stdout.println(`Widget: ${widgetPrice}`)

      //Look up missing key — returns the default
      missingPrice <- prices.getOrDefault("Unknown", 0.0)
      stdout.println(`Unknown: ${missingPrice}`)

      //Check size
      stdout.println(`Size: ${length prices}`)

      //Iterate over all entries
      for entry in prices
        stdout.println($entry)

      //Check if a key exists via getOrDefault
      fallback <- 0.0
      found <- prices.getOrDefault("Gadget", fallback)
      if found <> fallback
        stdout.println(`Gadget found: ${found}`)

Common mistakes

E50060 — Dict has no get() method, so calling prices.get("Widget") is unresolved — use getOrDefault(key, defaultValue) instead. See ek9 -h E50060 for details.

Incorrect:

prices.get("Widget")

Correct:

prices.getOrDefault("Widget", 0.0)
Other ways to ask this
  • Write code to build a dictionary and retrieve values safely
  • I need a key-value map with add, lookup, and size operations in EK9
  • In Python I'd use dict[key] = value and dict.get(key, default). Write the EK9 Dict equivalent
  • Given a mapping of product names to prices, show Dict creation, adding, and lookup

Coming from another language?

Python: dict[k] = v, dict.get(k, default). Java: map.put(k, v), map.getOrDefault(k, default). Go: m[k] = v, if val, ok := m[k]. EK9: += DictEntry(k, v), getOrDefault(k, fallback).

Keywords: lookup, Dict, add, map, key-value, getOrDefault, DictEntry