Skip to content

Instantly share code, notes, and snippets.

@b4oshany
Created January 7, 2017 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b4oshany/42cd7b4a9bbb1a78af95bbb5a3f024af to your computer and use it in GitHub Desktop.
Save b4oshany/42cd7b4a9bbb1a78af95bbb5a3f024af to your computer and use it in GitHub Desktop.
Regex to dict
>>> import re
>>> data = """1foo bar
... 2bing baz
... 3spam eggs
... nomatch
... """
>>> pattern = r"(.)(\w+)\s(\w+)"
>>> {x[0]: x[1] for x in (m.group(3, 2) for m in (re.search(pattern, line) for line in data.splitlines()) if m)}
{'baz': 'bing', 'eggs': 'spam', 'bar': 'foo'}
share improve t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment