[英]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.chain和join多一点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.