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


Groups > comp.lang.python > #80338

help with creating dict from string

Newsgroups comp.lang.python
Date 2014-11-06 08:37 -0800
Message-ID <cc511471-6929-4f15-8b07-5db374103e1a@googlegroups.com> (permalink)
Subject help with creating dict from string
From Tim <jtim.arnold@gmail.com>

Show all headers | View raw


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


Back to comp.lang.python | Previous | Next — Next 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