Iterate over a Dict and print each key-value pair.

← Collections and Data Structures · Ref: Q1158

for-in iterates over DictEntry objects:

  for entry in ages
    stdout.println($entry)

Each entry displays as key=value. See Q1161 for full Dict operations.

Example

defines module qa.collections.dictiteration

  defines program

    DictIterationDemo()
      stdout <- Stdout()

      ages <- Dict() of (String, Integer)
      ages += DictEntry("Alice", 30)
      ages += DictEntry("Bob", 25)
      ages += DictEntry("Charlie", 35)

      //Print the whole Dict
      stdout.println($ages)

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

Common mistakes

E01010 — Dict type parameters need parentheses: Dict() of (K, V).

Incorrect:

      ages <- Dict() of String, Integer

Correct:

      ages <- Dict() of (String, Integer)
Other ways to ask this
  • I need to loop through all entries in a dictionary
  • In Python I'd use for k, v in dict.items(). Write the EK9 Dict iteration
  • Given a Dict of names to ages, print each entry using for-in
  • Traverse a Dict and access each key-value pair as a DictEntry

Coming from another language?

Python: for k, v in dict.items(). Java: for (Map.Entry<K,V> e : map.entrySet()). Go: for k, v := range m. EK9: for entry in dict.

Keywords: iterate, loop, key-value, entry, Dict, for-in