Say you have,
foo = 'bar'
d = {'a-key':'a-value'}
And you want
d = {'a-key':'a-value','foo':'bar'}
e = {'foo':foo}
I know you can do,
d['foo'] = foo
#Either of the following for e
e = {'foo':foo}
e = dict(foo=foo)
But, in all these way to add the variable foo to dict, I have had to use the word foo twice; once to indicate the key and once for its value.
It seems wasteful to me to use foo twice. Is there a simpler way, in which you can tell python “Add this variable to the dictionary with its name as the key and its value as the value”?
Actutally using
footwice is remarkably common in python programs. It is used extensively for passing on arguments egWhich is a specialised case of the dictionary manipulations in your question.
I don’t think there is a way of avoiding it without resorting to magic, so I think you’ll have to live with it.