dicts & lists together

Pierre Barbier de Reuille pierre.barbier at cirad.fr
Wed Nov 3 02:37:55 EST 2004


Brad Tilley a écrit :
> Larry Bates wrote:
> 
>> Brad Tilley 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?
>>
>>
>>
>>  >>> xdict={'abc': 1, 'xyz':2, '123':3}
>>  >>> xlist=['abc', 'xyz', '123']
>>  >>> tlist=[xdict.get(v, None) for v in xlist]
>>  >>> print tlist
>> [1, 2, 3]
>>
>> Larry Bates
>> Syscon, Inc.
> 
> 
> Thank you Larry, I don't understand it, but it works ;)

If you don't understand what Larry's solution does, you probably should 
have a look there :

http://www.python.org/doc/2.3.4/tut/node7.html#SECTION007140000000000000000

or look in the web for "list comprehensions" in Python.

Pierre



More information about the Python-list mailing list