[Tutor] python equivalent to perl hash slices?

Bill Campbell bill at celestial.net
Wed Aug 4 01:34:22 CEST 2004


On Tue, Aug 03, 2004, Danny Yoo wrote:
>
>> 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)]
>> ###
>
>Hi Bill,
>
>Gah!  That's wrong!  *grin*

A mistake!  I've never made one of those (a few million maybe :-).

>I'm sorry; I must have been daydreaming.  The above produces a list of
>key-value pairs, but that's not a dict.  So needs one more thing:
>dict():
>
>###
>>>> cols = ['zero', 'one', 'two', 'three', 'four', 'five']
>>>> vals = [0, 1, 2, 3, 4, 5]
>>>> d = dict(zip(cols, vals))
>>>> d
>{'three': 3, 'two': 2, 'four': 4, 'zero': 0, 'five': 5, 'one': 1}
>###
>
>And now we have a dictionary.

I remember now reading about zip in the O'Reilly ``Learning
Python'' book, and thinking it might be useful.

One could then get the array slice for values with something like this, or
is there an easier way?

>>> map((lambda k: d.get(k, None)), cols)

Bill
--
INTERNET:   bill at Celestial.COM  Bill Campbell; Celestial Software LLC
UUCP:               camco!bill  PO Box 820; 6641 E. Mercer Way
FAX:            (206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676
URL: http://www.celestial.com/

``The children who know how to think for themselves spoil the harmony of
the collective society that is coming, where everyone would be
interdependent.''  1899 John Dewey, educational philosopher, proponent of
modern public schools.


More information about the Tutor mailing list