【问题标题】:Initialize an empty dictionary and print to txt初始化一个空字典并打印到txt
【发布时间】:2017-08-02 15:32:27
【问题描述】:

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

我怎样才能做到这一点,然后输出一个文本文件,其中每个键:值对是 utf-8 编码文本文件中的一个新行?每行应打印为“key,value”,不带引号或空格。

这是我目前所拥有的:

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

【问题讨论】:

  • 您是在打印之后还是之前填写值?
  • 在我最终打印字典之前,我会添加值
  • 您是否有理由不想在生成键值对时添加它们?是否有一些键无法获取值但仍需要打印?
  • 我想稍后添加这些值的唯一原因是我还没有它们。请看link

标签: python dictionary text


【解决方案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
# ...

【讨论】:

  • 文件中的任何地方都不应有空格。看起来这个解决方案只会在每行 k 和 v 之间留一个空格?
  • 我已经实现了这个改变。您只是想生成一个 CSV 文件吗?有一个内置库。
  • 不行,输出必须是文本文件
  • CSV 文件仍然是文本。
  • 对不起,我的意思是它必须是 .txt
【解决方案2】:

你可以试试这个:

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

【讨论】:

  • 我认为写文件的“正确”方式应该是使用 print 语句而不是 write。
【解决方案3】:
# 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

【讨论】:

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

    【讨论】:

      猜你喜欢
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      • 2019-06-17
      • 1970-01-01
      相关资源
      最近更新 更多