0

I have a string with values in the form key=value, separated by space, i.e.

my_string = "a=1 b=10 z=234 h=5"

what I need is to use a regex and store those value in a dictionary; so far I've done this:

my_dict = dict(re.findall(r'(\S+)=(".*?"|\S+)', my_string))
print(my_dict)

the problem is that print does not prints the item in the same order they appear in the string. so, due to my lack in python debugging knowledge, I don't know if is the findall() that stores values in my dictionary in a random order... or the print(). What I need is a way to store items in order, exactly as they appear in the string... maybe cycling through it. any suggestion will be appreciated, thank you very much

v_c
  • 55
  • 9

2 Answers2

0
>>> my_string
'a=1 b=10 z=234 h=5'
>>> import re
>>> "{"+re.sub(r'(\w+)=', r"'\1':", re.sub(r'\s+', ',', my_string))+"}"
"{'a':1,'b':10,'z':234,'h':5}"
>>> import ast
>>> ast.literal_eval("{"+re.sub(r'(\w+)=', r"'\1':", re.sub(r'\s+', ',', my_string))+"}")
{'a': 1, 'b': 10, 'h': 5, 'z': 234}
>>> type(ast.literal_eval("{"+re.sub(r'(\w+)=', r"'\1':", re.sub(r'\s+', ',', my_string))+"}"))
<class 'dict'>
>>> 
riteshtch
  • 8,629
  • 4
  • 25
  • 38
0

It's your dict that is introducing the unorderedness. Re.findall returns an list in the order of the matches. With the pattern you are using each entry in the list is itself a list (well, a tuple) of two values because you have two groups in the pattern. Simply use the return value of re.findall:

import re
my_string = "a=1 b=10 z=234 h=5"
matches = re.findall(r'(\S+)=(".*?"|\S+)', my_string)
print matches
for match in matches:
    print match

[('a', '1'), ('b', '10'), ('z', '234'), ('h', '5')]
('a', '1')
('b', '10')
('z', '234')
('h', '5')
  • so that's it. thank you... very much. I'm using python since 4 days and it's all new for me. may I ask you, does this list of tuples allow to have duplicates? i.e. [('a', '1'), ('b', '10'), ('a', '1'), ('z', '234'), ('h', '5')]. since some values in the string are duplicated (basically it's a packet with redundant fields). – v_c May 26 '16 at 08:10
  • Yes, a list can have duplicates. – DisappointedByUnaccountableMod May 26 '16 at 08:11