2014-06-09 13 views
5

Ho una funzione argomento parola chiave:argomenti pitone parole chiave con trattino

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. 

Come faccio a passare in parole chiave con un trattino? Non ho il controllo su queste parole chiave poiché sto analizzando queste da un database legacy esistente.

Grazie! -kumar

+0

Non si può avere le parole chiave con un trattino. – wim

+0

è una buona idea versione: http://stackoverflow.com/questions/16956364/function-accepts-keyword-arguments-that-are-not-identifiers –

risposta

12

Argomenti della parola chiave devono essere valid Python identifiers; questi non sono ammessi per - poiché è riservato per la sottrazione.

È possibile passare in stringhe arbitrarie utilizzando la **kwargs variable keyword argument syntax invece:

f1(**{"Attr1-SubAttr": "Val1", "Attr2": "Val2"}) 
+0

Grazie, ha funzionato! – Kumar

+0

Sei una rockstar, grazie. –

+0

Basta lasciare una nota: usato su Python Zeep, per passare un SOAP che aveva un nome con un trattino. – epx

Problemi correlati