0

I want to do something like this:

dict = {'a':1, 'b':2} 
def f(dict):
  return a + b

I am imagining something like Ruby's method missing, where I somehow make python search for any undefined terms as a string keyword in 'dict' before throwing an error. Is this possible?

EDIT: This is not a duplicate of the link above, but I need to clarify my question. Python keyword args allows for:

dict = {'a':1, 'b':2}
def f1(a, b):
  return a + b
f1(**dict)  # use ** to unpack
# Or use ** to pack args
def f2(**kwargs):
  return kwargs['a'] + kwargs['b']
f2(a=1, b=2)

What I am wondering about is exactly this:

def f(dict):
  return arbitrary1 + arbitrary2
f({'arbitrary1':1, 'arbitrary2':2})

Is there anyway I can make this work? I want to unpack the dict, but I don't want to have to change the method signature to match the contents of the dictionary.

Julian Irwin
  • 172
  • 10
  • 1
    Maybe you're looking for keyword arguments. http://docs.python.org/release/1.5.1p1/tut/keywordArgs.html – Steven Wexler Jan 06 '14 at 16:59
  • 3
    @steaks please don't link to tutorials for a version that's 15 years old. You probably mean http://docs.python.org/2.7/tutorial/controlflow.html#keyword-arguments – Daniel Roseman Jan 06 '14 at 17:01
  • It's not clear to me from your question **why** you'd want this, but what you describe could be achieved by using a dictionary and populating it with [`locals()`](http://docs.python.org/2/library/functions.html#locals) as well as keys and values from your function argument. `terms = {}; terms.update(locals()); terms.update(dct); return terms['a']` – Lukas Graf Jan 06 '14 at 19:02
  • Also, since what I posted above will still `NameError` if the name isn't found in either locals or the dictionary argument, you might want to take a look at [`defaultdict`](http://docs.python.org/2/library/collections.html#defaultdict-objects). – Lukas Graf Jan 06 '14 at 19:07

0 Answers0