7

we can convert the dictionary to kw using **kw but if I want kw as str(kw) not str(dict), as I want a string with keyword arguments for code_generator,

if I pass

obj.method(name='name', test='test', relation = [('id','=',1)])

I want a function to return the string like

"name='name', test='test', relation = [('id','=',1)]"
Javier
  • 60,510
  • 8
  • 78
  • 126
shahjapan
  • 13,637
  • 22
  • 74
  • 104

2 Answers2

13

The same syntax is used to accept arbitrary keyword arguments.

Python 2:

def somestring(**kwargs):
  return ', '.join('%s=%r' % x for x in kwargs.iteritems())

Python 3:

def somestring(**kwargs):
    return ", ".join(f"{key}={value}" for key, value in kwargs.items())

Note that dicts are arbitrarily ordered, so the resultant string may be in a different order than the arguments passed.

Richie Bendall
  • 7,738
  • 4
  • 38
  • 58
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

The upper answer can not run properly on python 2.7.16, it should be

def somestring(**kwargs):
    return ''.join([('%s=%s' % x) for x in kwargs.iteritems()]) 


#A full example:

def RunCommandAndEnsureZero(*args, **kwargs):
    retCode = RunCommand(*args, **kwargs)
    if retCode != 0:
        kwargsString = ''.join([('%s=%s' % x) for x in kwargs.iteritems()])
        raise Exception("error command: \"%s %s\"" % (''.join(args), kwargsString))
Alen Wesker
  • 237
  • 3
  • 6
  • use [] to let the generator run; then use the ("%s=%s" %x) to format a proper string formatting; finally join them – Alen Wesker Dec 21 '19 at 03:07