Re: help with creating dict from string
versalytics at gmail.com
versalytics at gmail.com
Thu Nov 6 17:09:18 EST 2014
On Thursday, November 6, 2014 12:41:10 PM UTC-5, Peter Otten wrote:
> Tim wrote:
>
> > hi, I have strings coming in with this format:
> >
> > '[one=two, three=four five, six, seven=eight]'
> >
> > and I want to create from that string, this dictionary:
> > {'one':'two', 'three':'four five', 'six':True, 'seven':'eight'}
> >
> > snip
>
> Not everything has to be a one-liner ;) If it works I don't think something
>
> >>> s = '[one=two, three=four five, six, seven=eight]'
> >>> def fix(pair):
> ... key, eq, value = pair.partition("=")
> ... return key.strip(), value if eq else True
> ...
> >>> dict(fix(t) for t in s.strip("[]").split(","))
> {'three': 'four five', 'seven': 'eight', 'one': 'two', 'six': True}
>
> is particularly inelegant. Are you sure that your grammar is not more
> complex than your example, e. g. that "," cannot occur in the values?
hi Peter,
I definitely wouldn't say that is inelegant :-)
I had never used the partition method and I didn't realize (or maybe remember) that strip could take a string of characters, not just one.
Oh yes, I am positive about the grammar--no commas are allowed in the values. I think your solution is pretty elegant. Thanks for your help!
--Tim
--
This is a very clever solution. I just came across the need for something similar. Good question, excellent solution. Thank you!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20141106/0def306c/attachment.html>
More information about the Python-list
mailing list