Menu
CoddyTech

entries and enumerate

Lesson 18 of 48 in Coddy's Python for Dart Developers course.

Dart Map.entries yields MapEntry objects with key and value properties. Python dict.items yields two-element tuples that a loop can unpack. Direct Python dict iteration yields keys only. Dart indexed iteration can use an explicit loop counter; Python enumerate pairs each value with a counter and accepts an optional starting label. That label does not change the underlying list indexes or skip values. Avoid changing dictionary size during traversal of its live views. When output needs stable ordering, distinguish insertion order from explicit sorting rather than relying on a counter to imply order.

Dart

void main() {
  final counts = {'red': 2};
  for (final entry in counts.entries) {
    print('${entry.key} ${entry.value}');
  }
  final labels = ['red', 'blue'];
  for (var i = 0; i < labels.length; i++) print('$i ${labels[i]}');
}

Python

counts = {'red': 2}
for key, value in counts.items():
    print(key, value)
for index, value in enumerate(['red'], start=1):
    print(index, value)

Porting trap

Python items is a method call, while Dart entries is a property. Preserve the correct access syntax for each API.

challenge icon

Challenge

Beginner

The single input line contains zero or more lowercase words separated by spaces. The supplied split() scaffold makes labels. Print one line per label as its one-based position, one space, then the label. Then print counts on its own line, followed by each distinct label and its frequency separated by one space, in first-seen order. Empty input prints only counts.

Your code goes in main.py. The locked driver.py starts your program and cannot be edited.

Try it yourself

# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module

run_module("main", run_name="__main__")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Dart Developers

Practice on your own: Online Python compiler