Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #80338 > unrolled thread

help with creating dict from string

Started byTim <jtim.arnold@gmail.com>
First post2014-11-06 08:37 -0800
Last post2014-11-07 14:50 -0500
Articles 5 — 4 participants

Back to article view | Back to comp.lang.python


Contents

  help with creating dict from string Tim <jtim.arnold@gmail.com> - 2014-11-06 08:37 -0800
    Re: help with creating dict from string Peter Otten <__peter__@web.de> - 2014-11-06 18:40 +0100
      Re: help with creating dict from string Tim <jtim.arnold@gmail.com> - 2014-11-06 11:18 -0800
        Re: help with creating dict from string <versalytics@gmail.com> - 2014-11-06 22:09 +0000
    Re: help with creating dict from string Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2014-11-07 14:50 -0500

#80338 — help with creating dict from string

FromTim <jtim.arnold@gmail.com>
Date2014-11-06 08:37 -0800
Subjecthelp with creating dict from string
Message-ID<cc511471-6929-4f15-8b07-5db374103e1a@googlegroups.com>
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'}

These are option strings, with each key-value pair separated by commas.
Where there is a value, the key-value pair is separated by '='.

This is how I started (where s is the string):
    s = s.replace('[','').replace(']','')
    s = [x.split('=') for x in s.split(',')]

    [['one', 'two'], [' three', 'four five'], [' six'], [' seven', 'eight']]

I know I can iterate and strip each item, fixing single-element keys as I go.

I just wondered if I'm missing something more elegant. If it wasn't for the leading spaces and the boolean key, the dict() constructor would have been sweet.

thanks for any ideas,
--Tim


[toc] | [next] | [standalone]


#80340

FromPeter Otten <__peter__@web.de>
Date2014-11-06 18:40 +0100
Message-ID<mailman.15549.1415295657.18130.python-list@python.org>
In reply to#80338
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'}
> 
> These are option strings, with each key-value pair separated by commas.
> Where there is a value, the key-value pair is separated by '='.
> 
> This is how I started (where s is the string):
>     s = s.replace('[','').replace(']','')
>     s = [x.split('=') for x in s.split(',')]
> 
>     [['one', 'two'], [' three', 'four five'], [' six'], [' seven',
>     [['eight']]
> 
> I know I can iterate and strip each item, fixing single-element keys as I
> go.
> 
> I just wondered if I'm missing something more elegant. If it wasn't for
> the leading spaces and the boolean key, the dict() constructor would have
> been sweet.

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?

[toc] | [prev] | [next] | [standalone]


#80341

FromTim <jtim.arnold@gmail.com>
Date2014-11-06 11:18 -0800
Message-ID<eb42036a-e89a-45c8-83c0-72fab2c20a16@googlegroups.com>
In reply to#80340
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

[toc] | [prev] | [next] | [standalone]


#80343

From<versalytics@gmail.com>
Date2014-11-06 22:09 +0000
Message-ID<mailman.15550.1415312060.18130.python-list@python.org>
In reply to#80341

[Multipart message — attachments visible in raw view] — view raw

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!

[toc] | [prev] | [next] | [standalone]


#80380

FromDennis Lee Bieber <wlfraed@ix.netcom.com>
Date2014-11-07 14:50 -0500
Message-ID<mailman.15574.1415389849.18130.python-list@python.org>
In reply to#80338
On Thu, 6 Nov 2014 08:37:00 -0800 (PST), Tim <jtim.arnold@gmail.com>
declaimed the following:

>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'}
>
>These are option strings, with each key-value pair separated by commas.
>Where there is a value, the key-value pair is separated by '='.
>
>This is how I started (where s is the string):
>    s = s.replace('[','').replace(']','')
>    s = [x.split('=') for x in s.split(',')]
>
>    [['one', 'two'], [' three', 'four five'], [' six'], [' seven', 'eight']]

	You state you want a dictionary -- so why are you mucking about with
generating a list of lists?

>>> inp = "[one=two, three=four five, six, seven=eight]"
>>> 
>>> inp = inp.strip("[]")
>>> inp
'one=two, three=four five, six, seven=eight'
>>> entries = inp.split(",")
>>> entries
['one=two', ' three=four five', ' six', ' seven=eight']
>>> for entry in entries:
... 	kv = entry.split("=")
... 	if len(kv) < 2:
... 		dct[kv[0].strip()] = True
... 	else:
... 		dct[kv[0].strip()] = kv[1].strip()
... 
>>> print dct
{'seven': 'eight', 'six': True, 'three': 'four five', 'one': 'two'}

	Note: this is a dictionary -- by definition the order of the k-v pairs
is not predefined, and may change with each pair that is added (though it
is peculiar that for this data set the display returns in reverse order).

>
>I know I can iterate and strip each item, fixing single-element keys as I go.

	It's simple, it is easy to understand, and way more elegant than trying
to create some PERLism.
-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
    wlfraed@ix.netcom.com    HTTP://wlfraed.home.netcom.com/

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web