On 3/1/2010 1:07 PM, Raphael Mayoraz wrote:
John Posner wrote:
On 2/26/2010 6:32 PM, Raphael Mayoraz wrote:
Hello,

I'd like to define variables with some specific name that has a common
prefix.
Something like this:

varDic = {'red': 'a', 'green': 'b', 'blue': 'c'}
for key, value in varDic.iteritems():
'myPrefix' + key = value


No trick, just swap a new key-value pair for each existing pair:

for key, value in varDic.iteritems():
varDic[myPrefix + key] = value
del varDict[key]

Just make sure that *myPrefix* isn't an empty string!

-John
Thanks for your answer.
However, your solution changes the key name in the dictionary.
That's not what I want I need to do. What I want is to define a new
variable which name is define as a string: 'myPrefx' + key. In the example
I give, I would get 3 variables:
myPrefixred = a
myPrefixgreen = b
myPrefixblue = c

Yes, I misinterpreted your request. I believe there's a consensus around here that you shouldn't even try to accomplish your goal. Instead of creating *myPrefixred* as a (module-)global name or a (function-)local name, you should just use the dictionary as-is: *varDict['red']*. Or maybe make the names into attributes of a class, as Alex Goretoy suggested. [1]

Can you present a convincing argument as to why you really, really need to use the name *myPrefixred* ?

-John

[1] http://mail.python.org/pipermail/python-list/2010-February/1237736.html



--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to