合并字典并为每个字典键创建 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'])
 }

对于字典中的每个键,txt 文件应包含来自字典 1 和字典 2 的键值,如下所示(来自键“1”的值):

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

因为必须删除 dict2 的 header 和索引,所以我尝试使用此问题中的代码(答案 1 中的代码),而是使用 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") 

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

感谢您的帮助!!

使用带有参数 sepfileprint 怎么样?

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)

在这里,星号 *unpacking operator

1.txt:

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