dicts & lists together

Bengt Richter bokr at oz.net
Tue Nov 2 20:24:34 CET 2004


On Tue, 02 Nov 2004 13:45:38 -0500, Brad Tilley <bradtilley at gmail.com> wrote:

>I have a dict that associates strings to numbers like this {'abc': 1, 
>'xyz':2, '123':3,...} I am then given a list of strings ['abc', 'xyz', 
>'123',...] and asked to associate a number to each string in the list 
>according to the string's value in the dict. I am at a loss as to how to 
>do this, can someone show me where to start?

Associate as in list of number,string pairs?

 >>> dct = {'abc':1, 'xyz':2, '123':3}
 >>> strings = ['abc','xyz','123','error']
 >>> [(dct[s],s) for s in strings]
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 KeyError: 'error'
 >>> [(dct.get(s, 99999),s) for s in strings]
 [(1, 'abc'), (2, 'xyz'), (3, '123'), (99999, 'error')]

Regards,
Bengt Richter



More information about the Python-list mailing list