python - how to print dict values based on key containing delimiters -


actually have dict

x1={'b;0':'a1;b2;c3','b;1':'aa1;aa2;aa3','a;1': 'a1;a2;a3', 'a;0': 'a;b;c'} 

actually here convention 'a;0','b;0' contain tags , 'a;1','b;1' have corresponding values, based on have group , print. dict output want is

<a>       #this group name <a>a1</a> # tags n values <b>a2</b> <c>a3</c> </a> <b> <a1>aa1</a1> <b2>aa2</b2> <c1>aa3</c1> </b> 

this sample dict given many groups may come c;0:.... d;0.....

i using code a=[] b=[] c=[] d=[] e=[] k,v in x1.iteritems(): if k.split(";").count('0')==1: # using bcoz a;0,b;0 contains tag checking if contain 0 split it. a=k.split(";") # contains a=['a','0','b','0'] b=v.split(";") # contains 'a;0','b;0' values else: c=v.split(";") # contains 'a;1','b;1' values in range(0,len(b)): d=b[i] e=c[i] print "<%s>%s<%s>"%(c,e,c) code working 50% when single group in dict('a;1': 'a1;a2;a3', 'a;0': 'a;b;c') , when multiple groups r in dict ('b;0':'a1;b2;c3','b;1':'aa1;aa2;aa3','a;1': 'a1;a2;a3', 'a;0': 'a;b;c') in both cases prints aa1 aa2 aa3 printing recent value not values

be aware: dictionaries have no order. iteritems() loop not start 'b;0'. try example

for k,v in x1.iteritems():     print k 

to see. on computer gives

a;1 a;0 b;0 b;1 

this gives problem since code assumes keys come in order appear in definition of x1 [edit: or rather come in order]. can e.g. iterate on sorted keys instead:

for k in sorted(x1.keys()):     v = x1[k]     print k, v 

then problem order solved. think have more problems in code.

edit: data structures:

it might better store data in way like

 x1 = {'a': [('a','a1'),('b','a2'),('c','a3')], 'b': ... } 

if cannot change format, how convert data:

x1f = {} k in x1.iterkeys():     tag, id = k.split(';')     if int(id) == 0:         x1f[tag] = zip(x1[k].split(';'), x1[tag+';'+'1'].split(';')) print x1f 

from there should easier convert desired output.

and depending if want extend complexity of output in future, might want consider using pyxml:

from xml.dom import minidom doc = minidom.document() 

then can use createelement , appendchild methods.


Comments

Popular posts from this blog

delphi - How to convert bitmaps to video? -

jasper reports - Fixed header in Excel using JasperReports -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -