kumar s wrote:
> Dear group,
> 
> unfortunately my previous post got tagged as
> 'homework' mail and got no responses. 
> 
> In short, I have a dictionary structure as depicted
> below. 
> 
> I want to go over every key and print the key,value
> pairs in a more sensible way. 
> 
> I have written a small piece of code. May I request
> tutors to go through it and comment if it is correct
> or prone to bugs. 
> 
> Thank you. 
> kum
> 
>>>> md = {(21597133, 21597325): [['NM_032457']], 
> (21399193, 21399334): [['NM_032456'], ['NM_002589']], 
> (21397395, 21399192): [['NM_032457'], ['NM_032456'],
> ['NM_002589']], 
> (21407733, 21408196): [['NM_002589']], 
> (21401577, 21402315): [['NM_032456']], 
> (21819453, 21820111): [['NM_032457']], 
> (21399335, 21401576): [['NM_032457'], ['NM_032456'],
> ['NM_002589']]}
> 
>>>> for item in md.keys():
>       mlst = []
>       for frnd in md[item]:
>               for srnd in frnd:
>                       mlst.append(srnd)
>       mystr = ','.join(mlst)
>       print(('%d\t%d\t%s')%(item[0],item[1],mystr))

This is OK but it could be shorter. I usually use dict.items() when I 
need both the keys and values of a dictionary. The nested lists seem to 
always have one item in them so maybe you could pull that out directly 
instead of with a for loop. Then a list comprehension would make the 
code more concise. So I would write this more this way:

for key, value in md.items():
   mlst = [ frnd[0] for frnd in value ]
   mystr = ','.join(mlst)
   print(('%d\t%d\t%s')%(key[0],key[1],mystr))

This is not more correct, just more concise.

Also if you care about the order of the output you could easily sort it 
using
for key, value in sorted(md.items()):

Kent

> 
>       
> 21597133      21597325        NM_032457
> 21399193      21399334        NM_032456,NM_002589
> 21397395      21399192        NM_032457,NM_032456,NM_002589
> 21407733      21408196        NM_002589
> 21401577      21402315        NM_032456
> 21819453      21820111        NM_032457
> 21399335      21401576        NM_032457,NM_032456,NM_002589
> 
> 
>       
> ____________________________________________________________________________________Fussy?
>  Opinionated? Impossible to please? Perfect.  Join Yahoo!'s user panel and 
> lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 
> 
> _______________________________________________
> Tutor maillist  -  [email protected]
> http://mail.python.org/mailman/listinfo/tutor
> 

_______________________________________________
Tutor maillist  -  [email protected]
http://mail.python.org/mailman/listinfo/tutor

Reply via email to