Reputation: 12017
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
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
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