Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Convert multiple instances of the same key into multiple rows

Tags:

python

I am trying to process a file that looks more or less like this:

f=0412345678 t=0523456789 t=0301234567 s=Party! flag=urgent flag=english id=1221AB12

I know I can for example use Python shlex to parse those without major issues with something like:

entry = "f=0412345678 t=0523456789 t=0301234567 s=Party! flag=urgent flag=english id=1221AB12"

line = shlex.split(entry)

I can then do a for loop and iterate over the key value pairs.

row = {}
for kvpairs in line:
    key, value = kvpairs.split("=")
    row.setdefault(key,[]).append(value)
print row

Results in:

{'id': ['1221AB12'], 's': ['Party!'], 'flag': ['urgent', 'english'], 't': ['0523456789', '0301234567'], 'f': ['0412345678']}

So far so good but I am having trouble finding an efficient way of outputting the original line so that the output looks like:

id=1221AB12 f=0412345678 t=0523456789 s=Party! flag=urgent 
id=1221AB12 f=0412345678 t=0523456789 s=Party! flag=english
id=1221AB12 f=0412345678 t=0301234567 s=Party! flag=urgent 
id=1221AB12 f=0412345678 t=0301234567 s=Party! flag=english
like image 504
Andre de Miranda Avatar asked May 13 '15 11:05

Andre de Miranda


1 Answers

product from itertools and

from itertools import product
from collections import OrderedDict
a = OrderedDict({'id': ['1221AB12'], 's': ['Party!'], 'flag': ['urgent', 'english'], 't': ['0523456789', '0301234567'], 'f':              ['0412345678']})
res = product(*a.values())
for line in res:
    print " ".join(["%s=%s" % (m, n) for m,n in zip(a.keys(), line) ])

result

s=Party! f=0412345678 flag=urgent id=1221AB12 t=0523456789
s=Party! f=0412345678 flag=urgent id=1221AB12 t=0301234567
s=Party! f=0412345678 flag=english id=1221AB12 t=0523456789
s=Party! f=0412345678 flag=english id=1221AB12 t=0301234567
like image 61
valentin Avatar answered Nov 14 '22 15:11

valentin