[Tutor] python equivalent to perl hash slices?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Aug 3 23:49:52 CEST 2004



On Tue, 3 Aug 2004, Bill Campbell wrote:

> Is there a python equivalent to perl's hash slices which I use
> extensively to simplify jobs such as parsing tabular data.

Hi Bill,



Not directly; the reason that something like:

###
>>> mapping = {0: 'zero', 1: 'one', 2:'two', 3:'three', 4:'four',
...            5: 'five', 6: 'six', 7:'seven', 8:'eight', 9:'nine'}
>>>
>>> mapping[3,1,4,1,5,9,2,6]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: (3, 1, 4, 1, 5, 9, 2, 6)
###

doesnt work is because sequences are perfectly possible as "composite
keys" in Python.  This is useful when we want to do something representing
a table or graph:

###
>>> sparse_graph = {}
>>> sparse_graph[0, 0] = 'origin'
>>> sparse_graph[1, 42] = 'point1'
>>> sparse_graph[-3, 17] = 'point2'
###



There's no built-in, as far as I remember, for doing dictionary slices in
Python.


That being said, your particular code example can be written with zip(),
since you have a list of keys and values, and you want to just put them
together.  Here's an example of zip():

###
>>> zip(["zero", "one", "two", "three", "four", "five"],
...     [0, 1, 2, 3, 4, 5])
[('zero', 0), ('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five',
5)]
###

This should allow you to transcribe:

    @record{@fields} = split("\t");  ## Perl

as something like:

    record = zip(fields, line.split('\t'))  ## Python



The other part of code gets a list of values, given a list of keys.  That
can be handled by something like this:

###
>>> def dict_slice(d, keys):
...     return map(d.get, keys)
...
###


For example:

###
>>> dict_slice({0: 'zero', 1: 'one', 2:'two', 3:'three', 4:'four',
...             5: 'five', 6: 'six', 7:'seven', 8:'eight', 9:'nine'},
...            [3,1,4,1,5,9,2,6])
['three', 'one', 'four', 'one', 'five', 'nine', 'two', 'six']
###


Hope this helps!



More information about the Tutor mailing list