[Tutor] Merge a dictionary into a string

Valerio Pachera valerio at pbds.eu
Sat Mar 16 13:39:13 EDT 2019


Consider this:

import collections
d = OrderedDict(a='hallo', b='world')

I wish to get a single string like this:

'a "hallo" b "world"'

Notice I wish the double quote to be part of the string.
In other words I want to wrap the value of a and b.

I was thinking to use such function I created:

def mywrap(text, char='"'):
    return(char + text + char)

I can't think anything better than

s = ''
for k, v in d.items():
     s += ' '.join( (k, mywrap(v)) ) + ' '

or

s = ''
for k, v in d.items():
    s += k + ' ' + mywrap(v) + ' '

What do you think?
It's fine enough but I wonder if there's a better solution.

Thank you.


More information about the Tutor mailing list