简体   繁体   中英

how to save a dictionary in python to a text file separated by white spaces

Code description

    mydic={node.getId():(round(x0),round(y0))}
    print mydic.items()                          
    output = open('output.txt', 'ab+')
    for key, value in mydic.items():
        output.write(str(key))
        output.write(str(value))
        output.write("\n")    
    output.close()   

Output-text file

Deepu(794.0, 586.0)

Facebook(800.0, 329.0)

LinkedIn(789.0, 768.0)

Google+(502.0, 671.0)

Viber(716.0, 559.0)

GoogleTalk(1093.0, 678.0)

Plus2(1072.0, 239.0)

Btech(534.0, 253.0)

Mtech(788.0, 136.0)

Desired Output (how is it possible-please help)

Deepu 794 586

Facebook 800 329

LinkedIn 789 768

Google+ 502 671

Viber 716 559

GoogleTalk 1093 678

Plus2 1072 239

Btech 534 253

Mtech 788 136

将for循环中的output.write()行更改为此:

output.write("{0} {1} {2}\n".format(str(key), str(value[0]), str(value[1]))

A little more pythonic with itertools.chain and join : Also note the conversion to ints.

mydic={
    "Deepu":(794.0, 586.0),
    "Facebook":(800.0, 329.0),
    "LinkedIn":(789.0, 768.0),
    "Google+":(502.0, 671.0),
    "Viber":(716.0, 559.0),
    "GoogleTalk":(1093.0, 678.0),
    "Plus2":(1072.0, 239.0),
    "Btech":(534.0, 253.0),
    "Mtech":(788.0, 136.0)
}

from itertools import chain
print "\n".join(" ".join(chain([key],[str(int(number)) for number in value])) for key,value in mydic.items())

Output:

Viber 716 559
Google+ 502 671
Facebook 800 329
LinkedIn 789 768
Plus2 1072 239
Mtech 788 136
Btech 534 253
Deepu 794 586
GoogleTalk 1093 678

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