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
BeginnerThe 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__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Dart Developers
1From Dart to Python
Run Your First Python ProgramInterpolation and printvar, final, and Python NamesFloor Versus TruncationBraces and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
for-in and rangeentries and enumerateLoop Updates and continuewhere, map, and List BuildingRecap: Build a Ranking2Values and Decisions
Null Safety and NoneList Equality ChangesConditions and Null DefaultsTernaries and elifRecap: Eligibility Rules3Collections and References
Lists and Negative IndexesRecords and Tuple UnpackingMap Lookups and KeyErrorSets and Shared ObjectsRecap: Clean an Inventory6Reliable Python Programs
stdin and Exact Formattingon, catch, finally, and withLibraries and Import ExecutionStatic Types Versus HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler