[Python-ideas] Syntax for key-value iteration over mappings

Andrew Barnert abarnert at yahoo.com
Tue Jul 28 03:29:21 CEST 2015


On Jul 27, 2015, at 21:17, Steven D'Aprano <steve at pearwood.info> wrote:
> 
> Keys and indices are not the same thing, and Python is not Lua.

It may be worth doing a survey of other languages to see how they handle this.

I think the most common thing is to have dict iteration yield either (key, value) pairs, especially in languages with pattern matching or at least basic Python-style tuple decomposition. For example, in Swift, you write `for (key, val) in d {...}`.

Another common thing in more Java-ish languages is to yield special item objects, like C# KeyValuePair<T>, which you'd use as `foreach(var item in myDictionary { spam(item.Key, item.Value); }`.

Some languages treat dictionaries as iterables of keys, like Python.

PHP does have something like this proposal: `foreach ($d as $k=>$v) {...}` vs. `foreach ($d as $k) {...}`. So does Go, although its syntax is `k, v` for a key-value pair vs. `k` for just the key (which obviously wouldn't work with Python-style tuple decomposition). I vaguely remember Tcl having something relevant here but I can't remember what it was.

The only other language I can think of that does anything like allowing you treat a list as a mapping from indices is JS (and its various offshoots), but their for loop is really treating everything as an object, iterating both keys and methods (since they're both the same thing), and in the case of an array you get the indices in arbitrary order, which is why documentation tells you that you probably don't want a for loop over an array. (They did add a foreach method to solve that, but it gives you key, index pairs for objects and value, index pairs for arrays.)

Anyway, if someone can think of a language that does what's being proposed here, it should be easier to find out whether users' experience with that feature is positive or negative.


More information about the Python-ideas mailing list