Python: convert multiple instances of the same key to multiple lines

I am trying to process a file that looks something like this:

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

I know that I can use Python shlex for parsing without significant issues with something like:

 entry = "f=0412345678 t=0523456789 t=0301234567 s=Party! flag=urgent flag=english id=1221AB12" line = shlex.split(entry) 

Then I can execute 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 itโ€™s hard for me to find an effective way to output the original string so that the result looks like this:

 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 
+6
source share
1 answer

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 
+5
source

Source: https://habr.com/ru/post/987129/


All Articles