[Tutor] Merge a dictionary into a string

Peter Otten __peter__ at web.de
Sat Mar 16 14:44:22 EDT 2019


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.

In Python 3.6 and above you can use f-strings:

>>> d = dict(a="hello", b="world")
>>> " ".join(f'{k} "{v}"' for k, v in d.items())
'a "hello" b "world"'

By the way, are you sure that the dictionary contains only strings without 
spaces and '"'?



More information about the Tutor mailing list