Reputation: 13254
Assume you have an awful long text. In the text there are acceleration values parse-able by the following regular expression. You would like to get the values out of the text (not necessarily with that regex, if you have a better way), and you would like the result to be a dictionary which matches strings to integers.
Example code which looks a little too complicated for a code base that is partly managed by non-python coders:
import re
long_text = "<an awful long text>Accel X, Y, Z: -39mg, 7mg, 789mg<which is not necessarily separated by line breaks or any kind of brackets>"
match = re.search("Accel X, Y, Z: (-?\d+)mg, (-?\d+)mg, (-?\d+)mg", a)
# described as unreadable by non-python colleagues:
desired_result = dict(zip(("x","y","z"),map(int,match.groups())))
Upvotes: 0
Views: 58
Reputation: 214949
Style questions are almost subjective, my personal preference is to avoid "smart" constructs and be explicit and verbose:
desired_result = {
'x': int(match.group(1)),
'y': int(match.group(2)),
'z': int(match.group(3))
}
Of course, if you had more keys, this would get really dumb at some point, but still I'd prefer a comprehension over map
:
result = {k: int(v) for k, v in zip("abcdefgh", match.groups())}
BTW, yours can be simplified down to
dict(zip("xyz",map(int,match.groups())))
No need for a tuple.
Upvotes: 2