1

I have a Python script that reads a string from a file which is have several key=value elements. An example is:

A=Astring,B=Bstring,C=Cstring

Is there an easy way to read this straight into a dictionary? Or would I have to manually build a dictionary after splitting by , and again by =.

Brett
  • 11,637
  • 34
  • 127
  • 213

2 Answers2

6

Split with a generator expression and the dict() function:

d = dict(entry.split('=') for entry in inputstring.split(','))

Demo:

>>> inputstring = 'A=Astring,B=Bstring,C=Cstring'
>>> dict(entry.split('=') for entry in inputstring.split(','))
{'A': 'Astring', 'C': 'Cstring', 'B': 'Bstring'}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
4

You can simply split based on , first and then for each item you can split based on =, like this

data = "A=Astring,B=Bstring,C=Cstring"
print dict(i.split("=") for i in data.split(","))
# {'A': 'Astring', 'C': 'Cstring', 'B': 'Bstring'}
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • Is there a performance advantage for passing a `list` to the `dict` function over a generator, like there is for the `.join` method of strings? I'm asking because of your "If the string is longer..." comment. – SethMMorton Feb 27 '14 at 16:37
  • @SethMMorton Yes. Please check this [answer](http://stackoverflow.com/a/9061024/1903116) – thefourtheye Feb 27 '14 at 16:40
  • 1
    @thefourtheye: No, that's not what Seth is asking. That answer shows the *exception*, where `str.join()` with a list comprehension is faster than a generator expression. **This is no such exception**. – Martijn Pieters Feb 27 '14 at 16:42
  • @thefourtheye: in other words, you are wasting cycles and memory here by using a list comprehension. There is no join here, `dict()` will just iterate over the generator expression and not build a list. – Martijn Pieters Feb 27 '14 at 16:43
  • @MartijnPieters Thanks for pointing out :) Removed that from the answer. – thefourtheye Feb 27 '14 at 16:55
  • @SethMMorton: No, there is no performance advantage here; the `dict()` constructor simply iterates over the first argument (if it is not a `dict` instance itself), so passing in a list comprehension or a generator makes little difference. A generator expression will take less memory. – Martijn Pieters Feb 27 '14 at 16:56