Rodrigo
Rodrigo

Reputation: 311

Split string of key=value into dictionary

I want to create a dictionary from a string that have key=value

s = "key1=value1 key2=value2 key3=value3"

print({r.split("=") for r in s})

Is it possible using dictionary comprehension? If yes, how?

Upvotes: 1

Views: 2100

Answers (2)

Sash Sinha
Sash Sinha

Reputation: 22360

You could use map:

>>> s = "key1=value1 key2=value2 key3=value3"
>>> d = {k: v for k, v in map(lambda i: i.split('='), s.split())}
>>> {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117856

You can first split on whitespace, then split on '='

>>> dict(tuple(i.split('=')) for i in s.split())
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

Upvotes: 4

Related Questions