help with explaining how to split a list of tuples into parts

Roy Smith roy at panix.com
Sat Jul 13 10:33:27 EDT 2013


In article <fba5dac7-963f-4c1b-b40b-c0a54d681530 at googlegroups.com>,
 peter at ifoley.id.au wrote:

> Hi List,
> 
> I am new to Python and wondering if there is a better python way to do 
> something.  As a learning exercise I decided to create a python bash script 
> to wrap around the Python Crypt library (Version 2.7).
> 
> My attempt is located here - https://gist.github.com/pjfoley/5989653

This looks like it should work, but it's a kind of weird use of list 
comprehensions.  Fundamentally, you're not trying to create a list, 
you're trying to select the one item which matches your key.  A better 
data structure would be a dict:

supported_hashes={'crypt':   (2,  '',    13),
                  'md5':     (8,  '$1$', 22),
                  'sha256':  (16, '$5$', 43),
                  'sha512':  (16, '$6$', 86),
                  }

then your selection logic becomes:

try:
    crypt_tuple = supported_hashes[args.hash]
except KeyError:
    print "unknown hash type"

Another thing you might want to look into is named tuples 
(http://docs.python.org/2/library/collections.html).  You could do 
something like:

from collections import namedtuple
HashInfo = namedtuple('HashInfo', ['salt_length',
                                   'hash_type',
                                   'expected_password_length'])

supported_hashes={'crypt':   HashInfo(2,  '',    13),
                  'md5':     HashInfo(8,  '$1$', 22),
                  'sha256':  HashInfo(16, '$5$', 43),
                  'sha512':  HashInfo(16, '$6$', 86),
                  }

and now you can refer to the tuple elements by name instead of by 
numeric index.



More information about the Python-list mailing list