In Python I use dict for key-value pairs. How do dictionaries work in EK9?

← Collections and Data Structures · Ref: Q1010

EK9 uses Dict of (KeyType, ValueType) for key-value pairs.

Python: scores = {'Alice': 95, 'Bob': 82}
EK9: scores <- {"Alice": 95, "Bob": 82}

Python: scores['Charlie'] = 78
EK9: scores += DictEntry("Charlie", 78)

Python: if 'Alice' in scores: print(scores['Alice'])
EK9: aliceScore <- scores.getOrDefault("Alice", 0)

       stdout.println($aliceScore)

Python: for key, value in scores.items(): print(f'{key}: {value}')
EK9: cat scores > stdout

Python: len(scores)
EK9: scores.length()

LITERAL SYNTAX:

EK9 supports dict literals with {key: value} syntax, just like Python.

ACCESS PATTERN:

Python raises KeyError on missing keys. EK9 uses getOrDefault(key, default) for safe access.

Example

defines module qa.collections.frompythondict

  defines program

    FromPythonDictDemo()
      stdout <- Stdout()

      // Like Python: scores = {'Alice': 95, 'Bob': 82}
      scores <- {"Alice": 95, "Bob": 82}

      // Like Python: for key, value in scores.items(): print(...)
      stdout.println("All scores:")
      cat scores > stdout

      // Like Python: scores.get('Alice', 0)
      aliceScore <- scores.getOrDefault("Alice", 0)
      stdout.println(`Alice's score: ${aliceScore}`)

      // Like Python: scores.get('Charlie', 0) — EK9 uses getOrDefault
      charlieScore <- scores.getOrDefault("Charlie", 0)
      stdout.println(`Charlie's score (default 0): ${charlieScore}`)

      // Like Python: len(scores)
      stdout.println(`Count: ${scores.length()}`)

Common mistakes

E50001 — EK9 has no [] indexing operator. Use getOrDefault(key, default) to safely access Dict values.

Incorrect:

      aliceScore <- scores["Alice"]

Correct:

      aliceScore <- scores.getOrDefault("Alice", 0)
Other ways to ask this
  • What is the EK9 equivalent of Python's dict?
  • How do I create and use a Dict in EK9?
  • How does EK9's Dict compare to Python's dictionary?

Coming from another language?

Python developers: dict maps to Dict of (K, V). Use {key: value} literals. Access with .get() and guard, not [] indexing.

Keywords: python, collection, migration, key value, dict, dictionary