合并字典并为每个字典键创建 txt 文件

原文标题merge dictionaries and create txt files for each dictionary keys

我想合并两个字典并为每个字典键创建一个 txt 文件。我的每个字典都有 100 多个键,所以这些只是一个示例:

dict1 = {
 '1': [3.84, 2, 4, 6, 7],
 '45': [4.9, 2, 5, 9, 9],
 '135': [6.7,2, 4, 7, 7]
}

dict2 = {
'1': pd.DataFrame([[101,        105,        106 ],
                    [245,        134,        96  ],
                    [175,        105,        200 ]], 
                columns=['AST_0-1'   ,'AST_10-1'   , 'AST_110-1']),

'45': pd.DataFrame([[101,        105,        106 ],
                    [245,        134,        96  ],
                    [175,        105,        200 ]],
                columns=['AST_0-45'  ,'AST_10-45'  , 'AST_110-45']),

'135': pd.DataFrame([[101,      105,        106   ],
                    [245,      134,        96    ],
                    [175,      105,        200   ]],
                columns=['AST_0-135' ,'AST_10-135' , 'AST_110-135'])
 }

对于 dict 中的每个键,txt 文件应包含来自 dict 1 和 dict 2 的键值,如下所示(来自键 ‘1’ 的值):

 3.84
 2
 4
 6
 7
101  105  106 
245  134  96
175  105  200

因为必须删除 dict2 的标头和索引,所以我尝试使用此问题中的代码(答案 1 中的代码)从数据帧的字典中创建 csv 并删除标头,但使用file_name = f”{k}.csv”,我使用了file_name = f”{k}.txt”,不确定这样做是否正确,但它确实创建了一个 txt 文件(我是 python 新手)。但是,最终的 txt 文件将 dict1 值作为列表。它看起来像这样:

[3.84, 2, 4, 6, 7]
101        105        106 
245        134        96
175        105        200

我还尝试使用以下代码创建 txt 文件:

 for key, value in dict1.items():
      filename=str(key + '.txt')
      with open(filename,"w") as f:
         for v in value:
             f.write(str(v) + "\n") 

我能够在不同的行中创建一个 dict1 的每个值的 txt 文件(如上面的示例),但我不确定如何在此代码中添加没有标题和索引的 dict2。

谢谢你的帮助!!

原文链接:https://stackoverflow.com//questions/71918779/merge-dictionaries-and-create-txt-files-for-each-dictionary-keys

回复

我来回复
  • j1-lee的头像
    j1-lee 评论

    print和参数sepfile怎么样?

    for k, v in dict1.items():
        with open(f"{k}.txt", "w") as f:
            print(*v, sep='\n', file=f)
            dict2[k].to_csv(f, sep='\t', header=False, index=False)
    

    这里,星号*是解包操作符。

    1.txt

    3.84
    2
    4
    6
    7
    101 105 106
    245 134 96
    175 105 200
    
    2年前 0条评论