Answer the question
In order to leave comments, you need to log in
How to write re python results to a dictionary?
Good afternoon.
Sorry for the idiotic question. I've already broken my head, but the feeling that the answer is very simple does not give me peace
There is a text
Vasya - 10
Vanya -20
Petya -30
I want to get
[{'name' : 'Vasya', 'value': 10},
{'name' : 'Vanya', 'value': 20},
{'name' : 'Peter', 'value': 30}]
Doing
res=[]
for i in text.split("/r"):
reg = re.match('(?P<type>.*) - (?P<value>.*)',i)
res.append(reg.groupdict())
Answer the question
In order to leave comments, you need to log in
# -*- coding: utf-8 -*-
import re
text = u"""Вася - 10
Ваня - 20
Петя - 30"""
d = dict(re.findall(u"^(.+?) - (\d+?)$", text, flags=re.M|re.U))
print d
p = re.compile(u"^(?P<name>.+?) - (?P<value>\d+?)$", flags=re.M|re.U)
d = [match.groupdict() for match in p.finditer(text)]
PS In general, you have two problems:
1) Only the first line contains "-", the other two contain "-". Regulator should be upgraded to:
2) Instead of "greedy" regular expressions like .* use ungreedy-versions .*? or .+?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question