Perl has a construct (called a “hash slice,” as Joe Z points out) for indexing into a list hash to get a list, for example:
%bleah = (1 => 'a', 2 => 'b', 3 => 'c'); print join(' ', @bleah{1, 3}), "\n";
Accomplished
gives:
ac
The simplest, most readable way that I know to get closer to this in Python would be list comprehension:
>>> bleah = {1: 'a', 2: 'b', 3: 'c'} >>> print ' '.join([bleah[n] for n in [1, 3]]) ac
because:
>>> bleah[[1, 2]] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list'
Is there any other, better way that I am missing? perhaps in Python3, with which I have not done anything yet? and if not, does anyone know if THE PEP has already been submitted for this? my google-fu could not find it.
"this is not Pythonic": yes, I know, but I would like it to be. it is concise and readable, and since it will never index Pythonic in a dict with a non-expandable type, the exception handler iterates over the index for you, and not barfing, will not break the current code itself.
Note: as mentioned in the comments, this test case can be rewritten as a list, completely eliminating the use of dict, but I'm looking for a general solution.