Suggestion: make sequence and map interfaces more similar
Terry Reedy
tjreedy at udel.edu
Thu Mar 31 13:41:19 EDT 2016
On 3/31/2016 10:13 AM, Marko Rauhamaa wrote:
> One could compose a table of correspondences:
with some corrections
> -------------------------------------------
> list (L) dict (D)
> -------------------------------------------
> L[key] = value D[key] = value
> del L[key] (*) del L[key]
> (*) reassigns all keys
> key >= 0 and key < len(L) key in D
'-len(L) <= key < len(L)' or 'key in range(-len(L), len(L)'
Lists, tuples, and ranges have 2 keys for each value,
though that is not guaranteed for sequences in general.
key in D == key in D.keys()
> range(len(L)) iter(D)
iter(range(Len(L)) == iter(D.keys())
> L.clear D.clear
> L.copy D.copy
> lambda key: L[key] D.get
The purpose of D.get() is to supply a default instead of raising
KeyError when key not in D. The lambda function above does not do that.
Turning subscripting into a function is a side-effect of D.get. A
generic get function:
def get(subscriptable, key, default=None):
try:
return subscriptable[key]
except (IndexError, KeyError):
return default
> lambda: enumerate(L) D.items
As I pointed out a couple days ago, an enumerate iterator is quite
different from a set-like dynamic view. An actual correspondence:
enumerate(L) iter(D.items())
Writing a set-like dynamic view of lists corresponding to D.values() or
D.items() would be an interesting project.
> lambda: range(len(L)) D.keys
iter(range(len(L)) iter(D.keys())
Already given above. Iterating indexes is now much rarer than iterating
dict keys.
--
Terry Jan Reedy
More information about the Python-list
mailing list