[Tutor] Merge a dictionary into a string
Mats Wichmann
mats at wichmann.us
Sun Mar 17 13:05:17 EDT 2019
On 3/16/19 11:39 AM, 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.
So the question that comes to mind is "why"? I don't mean that in the
negative sense as in you don't want to do that, but your use case may
drive the choice of possible solutions.
For example, I once got asked very nearly this question by someone who
it turned out wanted to serialize the dict into something that could
later be used to load up a dict. String is what he thought of, but in
this case json, or pickle, turned out to be a better solution for what
he wanted than a string.
If you only want to print the string for informational purposes, the
suggestions here will work well. You can even define your own class
which inherits from OrderedDict and just provides a new definition of
the method which produces a string representation and gives you what you
want without calling anything, like this:
>>> class MyOrderedDict(OrderedDict):
... def __repr__(self):
... return " ".join(f'{k} "{v}"' for k, v in self.items())
...
>>>
>>> d = MyOrderedDict(a='hallo', b='world')
>>> print(d)
a "hallo" b "world"
>>> x = str(d)
>>> x
'a "hallo" b "world"'
More information about the Tutor
mailing list