[Tutor] Merge a dictionary into a string
Alex Kleider
akleider at sonic.net
Sat Mar 16 18:51:24 EDT 2019
On 2019-03-16 10:39, Valerio Pachera wrote:
> 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.
>
Would the following not give you what you want:
(I've not used OrderedDict but I believe it would work for dict so
assume ok for OrderedDict.)
my_which_string = "a = '{a}' b = '{b}'".format(**d)
More information about the Tutor
mailing list