[Tutor] Merge a dictionary into a string

David L Neil PyTutor at danceswithmice.info
Sun Mar 17 15:12:50 EDT 2019


On 18/03/19 6:05 AM, Mats Wichmann wrote:
> 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.

Reading the OP, I immediately recognised the problem - meantime others 
had responded and the f'string' suggestion seemed most apropos.


Somewhat intrigued, and to answer the use-case question, I went looking 
in my personal collection of RDBMS routines and "snippets" (which have 
hardly been updated since Py2, excepting (IIRC) when MySQL's 
Connector-Python extended into dictionary-cursors).

The Connector will automatically delimit field/colNMs passed within a 
variable collection ('escaping' practice, highly recommended!) - a 
SELECT clause (for example). However, such automation is not applied to 
similar appearing in other clauses.

One of my helper-routines creates a comma-separated string by first 
surrounding columnNMs with back-ticks and then .join()ing. It's not 
rocket-surgery, but has been handy and import-ed many, many times.

YAGNI: me being me [puffs-out chest in a most unattractive fashion], one 
of the function's optional arguments offers a choice of delimiter. Can't 
recall ever using it 'elsewhere' though.


Thanks to the OP, and respondents making me think.
Have added to my >=v3.6 Backlog...
-- 
Regards =dn


More information about the Tutor mailing list