Home > Blockchain >  merge dictionaries and create txt files for each dictionary keys
merge dictionaries and create txt files for each dictionary keys

Time:04-19

I want to merge two dictionaries and create a txt files for each dictionary key. Each of my dictionaries have more than 100 keys so these are just an example:

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'])
 }

For each key in the dict, the txt file should contain the key values from dict 1 and dict 2 like this (values from key '1'):

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

Because the header and indexes of dict2 has to be removed I tried to use the code from this question (code in answer 1) create csv from dictionaries of dataframes and drop header but instead using file_name = f"{k}.csv" , I used file_name = f"{k}.txt", not sure if it was correct to do that but it did create a txt file (I am new in python). However the final txt files have the dict1 values as a list. It looks like this:

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

I also tried to create the txt files using this code:

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

I was able to create a txt file with each value of dict1 in a different line (like the example above) but I am not sure how to add the dict2 without the headers and indexes in this code.

Thanks for any help!!

CodePudding user response:

How about using print with parameters sep and file?

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)

Here, the star notation * is the unpacking operator.

1.txt:

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