1

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?

Rodrigo
  • 135
  • 4
  • 45
  • 107
  • I think the solution you're after is `{r.split('=')[0]: r.split('=')[1] for r in s.split()}`. But be aware that this will fail for inputs like: `a=2 b=Jhon Smith c=apple`. – Roy Cohen Dec 30 '21 at 16:50
  • 1
    possible duplicate of https://stackoverflow.com/questions/1246444/convert-string-to-dict-using-list-comprehension – AlirezaAsadi Dec 30 '21 at 16:50
  • Does this answer your question? [convert string to dict using list comprehension](https://stackoverflow.com/questions/1246444/convert-string-to-dict-using-list-comprehension) – Roy Cohen Dec 30 '21 at 16:53

2 Answers2

4

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

>>> dict(tuple(i.split('=')) for i in s.split())
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

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'}
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40