Brett
Brett

Reputation: 12017

Python - Convert a key-value string to a dictionary

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 =.

Upvotes: 1

Views: 1527

Answers (2)

thefourtheye
thefourtheye

Reputation: 239683

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'}

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1124968

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'}

Upvotes: 6

Related Questions