Dynamic variable creation from string

Nobody nobody at nowhere.com
Sun Dec 11 01:42:13 EST 2011


On Fri, 09 Dec 2011 01:55:28 -0800, Massi wrote:

> Thank you all for your replies, first of all my Sum function was an
> example simplifying what I have to do in my real funciton. In general
> the D dictionary is complex, with a lot of keys, so I was searching
> for a quick method to access all the variables in it without doing the
> explicit creation:
> 
> a, b, c = D['a'], D['b'], D['c']
> 
> and without using directly the D dictionary (boring...).

If just you're trying to avoid getting a repetitive strain injury in your
right-hand little finger from typing all the [''], you could turn
the keys into object attributes, e.g.:

	class DictObject:
	    def __init__(self, d):
	        for key, value in d.iteritems():
	            setattr(self, key, value)
	...
	o = DictObject(D)
	# use o.a, o.b, etc





More information about the Python-list mailing list