0

I have following dictionaries and wanted to save the values to appropriate columns

my_dict1= {'key1':'Yes','key2':'No', 'key3':12, 'key4':'Enabled', 'key5':'Single'}
my_dict2= {'key1':'Yes','key3':4, 'key4':'Disabled'}

I would like to save dictionary into CSV file such that CVS should like like

key1 | key2 | key3 | key4 | key5
Yes  | No   | 12   | Enabled | Single
Yes  | -   | 4    | Disabled | - 

2 Answers2

1

It can be done very easily using pandas module.

import pandas as pd

my_dict1= {'key1':'Yes','key2':'No', 'key3':12, 'key4':'Enabled', 'key5':'Single'}
my_dict2= {'key1':'Yes','key3':4, 'key4':'Disabled'}

data1 = pd.DataFrame.from_dict(my_dict1,orient='index').T
data2 = pd.DataFrame.from_dict(my_dict2,orient='index').T

data = pd.merge(data1,data2,how='outer')

data.to_csv('output_data.csv',index=False)
exiled
  • 305
  • 2
  • 11
0

You have to normalize your my_dict2 first. Below should work.

import csv

my_dict1= {'key1':'Yes','key2':'No', 'key3':12, 'key4':'Enabled', 'key5':'Single'}
my_dict2= {'key1':'Yes','key3':4, 'key4':'Disabled'}

keys = my_dict1.keys()

for k in keys:
    if not k in my_dict2.keys():
        my_dict2[k] = 'NA'

with open('output.csv', 'w', newline='')  as file:
    writer = csv.DictWriter(file, keys)
    writer.writeheader()
    writer.writerows([my_dict1, my_dict2])
bertdida
  • 4,988
  • 2
  • 16
  • 22