Bo Peng wrote:
Dear list,

I have many dictionaries with the same set of keys and I would like to write a function to calculate something based on these values. For example, I have

a = {'x':1, 'y':2}
b = {'x':3, 'y':3}

def fun(dict):
  dict['z'] = dict['x'] + dict['y']

fun(a) and fun(b) will set z in each dictionary as the sum of x and y.

My function and dictionaries are a lot more complicated than these so I would like to set dict as the default namespace of fun. Is this possible? The ideal code would be:

def fun(dict):
  # set dict as local namespace
  # locals() = dict?
  z = x + y
As you no doubt have discovered from the docs and this group, that isn't doable with CPython.

If you must write your functions as real functions, then you might do something like this:

 >>> a = {'x':1, 'y':2}
 >>> b = {'x':3, 'y':3}
 ...
 >>> def funa(x,y, **kw):
 ...     del kw     #Careful of unwanted names in locals with this approach
 ...     z = x + y
 ...     return locals()
 ...
 >>> a.update(funa(**a))
 >>> b.update(funa(**b))
 >>> a
{'y': 2, 'x': 1, 'z': 3}
 >>> b
{'y': 3, 'x': 3, 'z': 6}
 >>>


Alternatively, you could use exec:

 >>> a = {'x':1, 'y':2}
 >>> b = {'x':3, 'y':3}
 >>> exec "z = x + y" in globals(), a
 >>> a
{'y': 2, 'x': 1, 'z': 3}
 >>> exec "z = x + y" in globals(), b
 >>> b
{'y': 3, 'x': 3, 'z': 6}
 >>>

Michael

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

Reply via email to