简体   繁体   中英

printing a set for dictionary values - python

I'm having trouble formatting my output in python 3.0. The values are in a set for each key.

The output I have now is:

AAG -> ['AGA']
AGA -> ['GAT']
ATT -> ['TTC']
CTA -> ['TAC']
CTC -> ['TCT']
GAT -> ['ATT']
TCT -> ['CTA', 'CTC']
TTC -> ['TCT']

The output I need is:

AAG -> AGA
AGA -> GAT
ATT -> TTC
CTA -> TAC
CTC -> TCT
GAT -> ATT
TCT -> CTA,CTC
TTC -> TCT

This is what my code currently looks like. Also the dictionary has to be sorted by keys.

#sort lexigraphically by keys
for key in sorted(theDict):
    print("%s -> %s" % (key, theDict[key]))

You can join the values for each key as a string and then format it:

for key in sorted(theDict):
    print("%s -> %s" % (key, ','.join(theDict[key])))

theDict[key] is a list of strings, but you want to join the list into a single string before printing it. Try ','.join(theDict[key]) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM