LChaos2
LChaos2

Reputation: 177

Adding 2 dictionary entries from one string

Suppose I have the following code:

new_dict = {}
text = "Yes: No Maybe: So"

I want to split the string up into 2 dictionary elements like so:

new_dict = {'Yes':'No', 'Maybe':'So'}

I tried to split the string up into a list in the same fashion to get a brief idea on how to do it, but I haven't had much success.

Upvotes: 2

Views: 80

Answers (3)

jamylak
jamylak

Reputation: 133604

>>> import re
>>> text = "Yes: No Maybe: So"
>>> dict(re.findall(r'(\w+): (\w+)', text))
{'Maybe': 'So', 'Yes': 'No'}

or the more efficient:

>>> dict(m.groups() for m in re.finditer(r'(\w+): (\w+)', text))
{'Maybe': 'So', 'Yes': 'No'}

Upvotes: 1

eumiro
eumiro

Reputation: 212975

text = "Yes: No Maybe: So"
words = [w.rstrip(':') for w in text.split()]
new_dict = dict(zip(words[::2], words[1::2]))

Upvotes: 4

Sven Marnach
Sven Marnach

Reputation: 602035

If each colon is followed by a space, str.split() will work fine for you:

tokens = (s.rstrip(":") for s in text.split())
new_dict = dict(zip(tokens, tokens))

Upvotes: 2

Related Questions