14

I have a keyword argument function:

def f1(**kw):
    for key,val in kw.iteritems():
        print "key=%s val=%s" % (key,val)

f1(Attr1 = "Val1", Attr2 = "Val2")  # works fine.

f1(Attr1-SubAttr = "Val1", Attr2 = "Val2")  # complains about keyword being an expression.

f1("Attr1-SubAttr" = "Val1", Attr2 = "Val2")  # doesn't work either.

How do I pass in keywords with a hyphen? I don't have control over these keywords since I am parsing these from an existing legacy database.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
Kumar
  • 143
  • 1
  • 4

2 Answers2

34

Keyword arguments must be valid Python identifiers; these don't allow for - as that's reserved for subtraction.

You can pass in arbitrary strings using the **kwargs variable keyword argument syntax instead:

f1(**{"Attr1-SubAttr": "Val1", "Attr2": "Val2"})
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Just leaving a note: used this on Python Zeep, to pass a SOAP that had a name with dash. – epx Dec 06 '17 at 19:58
0

To make the above code to work in python 3 iteritems() replaced by items().

Makyen
  • 31,849
  • 12
  • 86
  • 121