Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将python中的词典保存到由空格分隔的文本文件中_Python - Fatal编程技术网

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

如何将python中的词典保存到由空格分隔的文本文件中,python,Python,代码说明 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))

代码说明

    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.0586.0)

Facebook(800.0329.0)

LinkedIn(789.0768.0)

谷歌+(502.0671.0)

毒蛇(716.0559.0)

谷歌谈话(1093.0678.0)

Plus2(1072.0239.0)

Btech(534.0253.0)

Mtech(788.0136.0)

所需输出(如何可能,请帮助)

迪普794586

Facebook 800 329

LinkedIn 789 768

谷歌+502671

维伯716559

谷歌对话1093678

Plus2 1072 239

Btech 534 253


Mtech 788 136将for循环中的
输出.write()
行更改为:

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

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

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

与和更具蟒蛇风格: 还要注意到int的转换

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

与和更具蟒蛇风格: 还要注意到int的转换

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

我认为你不需要
str
呼叫
format
应该可以处理这个问题。我认为你不需要
str
调用<代码>格式应该可以处理这个问题。