Is there a nicer way to do this?

Amaury Forgeot d'Arc afaNOSPAM at neuf.fr
Thu Oct 4 23:28:44 CEST 2007


Hello,
Stefan Arentz a écrit :
> Is there a better way to do the following?
> 
> attributes = ['foo', 'bar']
> 
> attributeNames = {}
> n = 1
> for attribute in attributes:
>    attributeNames["AttributeName.%d" % n] = attribute
>    n = n + 1
> 
> It works, but I am wondering if there is a more pythonic way to
> do this.
> 
>  S.

You could use enumerate() to number the items (careful it starts with 0):

   attributes = ['foo', 'bar']
   attributeNames = {}
   for n, attribute in enumerate(attributes):
       attributeNames["AttributeName.%d" % (n+1)] = attribute


Then use a generator expression to feed the dict:

   attributes = ['foo', 'bar']
   attributeNames = dict(("AttributeName.%d" % (n+1), attribute)
                         for n, attribute in enumerate(attributes))

Hope this helps,

-- 
Amaury



More information about the Python-list mailing list