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


Groups > comp.lang.python > #80380

Re: help with creating dict from string

From Dennis Lee Bieber <wlfraed@ix.netcom.com>
Subject Re: help with creating dict from string
Date 2014-11-07 14:50 -0500
Organization IISS Elusive Unicorn
References <cc511471-6929-4f15-8b07-5db374103e1a@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.15574.1415389849.18130.python-list@python.org> (permalink)

Show all headers | View raw


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/

Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread


Thread

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

csiph-web