初始化一个空字典并打印到txt

时间:2017-08-02 15:32:27

标签: python dictionary text

我想使用键" 001-100初始化一个空字典。"我稍后会填写这些值。

如何执行此操作然后输出一个文本文件,其中每个键:值对是utf-8编码文本文件中的新行?每行应打印为"键,值"没有引号或空格。

到目前为止我所拥有的:

# Initialize the predictions dictionary
predictions = dict() 

#Output the predictions to a utf-8 txt file
with io.open("market_basket_recommendations.txt","w",encoding='utf8') as recommendations:    
    print(predictions, file = 'market_basket_recommendations.txt')
    recommendations.close()

4 个答案:

答案 0 :(得分:1)

创建一个空字典

使用dict.from_keys()。它专门用于构建空字典。

predictions = dict.fromkeys("{:03}".format(i) for i in range(1, 101))
# {'001': None,
#  '002': None,
#  '003': None,
#  '004': None,
# ...

自行打印

比使用标准print功能更自然?您可以使用redirect_stdout

执行此操作
from contextlib import redirect_stdout

with open("market_basket_recommendations.txt", 'w') as file:
    with redirect_stdout(file):
        for k, v in p.items():
            print("{},{}".format(k, v))
#
# In market_basket_recommendations.txt:
#
# 001,None
# 002,None
# 003,None
# 004,None
# ...

答案 1 :(得分:0)

你可以试试这个:

d = {i:0 for i in range(1, 101)}

f = open('the_file.txt', 'a')

for a, b in d.items():
   f.write(str(a)+" "+b+"\n")

f.close()

答案 2 :(得分:0)

# Initialize the predictions dictionary
predictions = dict({
        'a': 'value',
        'another': 'value',
    }
) 

#Output the predictions to a utf-8 txt file
with open("market_basket_recommendations.txt", "w", encoding='utf8') as recommendations:
    for key in predictions:
        recommendations.write(key + ',' + predictions[key] + '\n')

输出:

another,value
a,value

答案 3 :(得分:0)

with open('outfile.txt', 'w', encoding='utf-8') as f:
    for k, v in predictions.items():
        f.write(k + "," + v)
        f.write('\n')