H
H
hawkkoff2014-04-13 00:20:04
Python
hawkkoff, 2014-04-13 00:20:04

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())

But I get only 1 element in the array. What's wrong? I would be grateful if you write a shorter solution. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Dugin, 2014-04-13
@hawkkoff

# -*- coding: utf-8 -*-
import re

text = u"""Вася - 10
Ваня - 20
Петя - 30"""

d = dict(re.findall(u"^(.+?) - (\d+?)$", text, flags=re.M|re.U))

print d

If you need a list of dictionaries, then, for example, like this:
p = re.compile(u"^(?P<name>.+?) - (?P<value>\d+?)$", flags=re.M|re.U)
d = [match.groupdict() for match in p.finditer(text)]

A
Andrey Dugin, 2014-04-13
@adugin

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 question

Ask a Question

731 491 924 answers to any question