簡體   English   中英

如何將python中的字典保存到由空格分隔的文本文件中

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

代碼說明

    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()   

輸出文本文件

迪普(794.0,586.0)

臉書(800.0,329.0)

領英(789.0,768.0)

谷歌+(502.0,671.0)

Viber(716.0,559.0)

GoogleTalk(1093.0,678.0)

加2(1072.0,239.0)

Btech(534.0,253.0)

科技(788.0,136.0)

所需的輸出 (如何可能,請幫助)

迪普794586

臉書800 329

領英789768

Google+ 502671

Viber 716559

GoogleTalk 1093 678

加號1072 239

Btech 534253

Mtech 788136

將for循環中的output.write()行更改為此:

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

使用itertools.chainjoin多一點pythonic :還請注意轉換為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())

輸出:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM