mohanakrishnavh
mohanakrishnavh

Reputation: 139

How to write two python dictionaries with common key to CSV file?

I have the below two dictionaries: dict1 = {'a':100,'b':200,'c':300} dict2 = {'a':0.20,'b':0.25,'c':0.30}

I want to write it into CSV as :

Key Value1 Value2
a 100 0.20
b 200 0.25
c 300 0.30

Upvotes: 0

Views: 145

Answers (2)

sgDysregulation
sgDysregulation

Reputation: 4417

You can write the dictionaries to a pandas data-frame, i.e. ```

from tabulate import tabulate
import pandas as pd

dict1 = {'a':100,'b':200,'c':300} 
dict2 = {'a':0.20,'b':0.25,'c':0.30}

df = pd.Series(dict1,name='Value 1').to_frame()
df['Value 2'] = dict2.values()
print(tabulate(df, headers= 'keys', tablefmt= 'grid'))

printing df generates

+----+-----------+-----------+
|    |   Value 1 |   Value 2 |
+====+===========+===========+
| a  |       100 |      0.2  |
+----+-----------+-----------+
| b  |       200 |      0.25 |
+----+-----------+-----------+
| c  |       300 |      0.3  |
+----+-----------+-----------+

A pandas series is a 1D data structure which converts the dictionary dict1 to a series with the dictionary keys as the index and the dictionary values as the series values. to_frame converts the series to a dataframe (2D data structure or a table) with one column, the line df['Value 2'] = dict2.values() adds dict2 as a second column in the dataframe df.
You can write the resulting dataframe to a csv file using

df.to_csv('filename here')

here is the result of dumping the file content using cat
image of the result of dumping the file content to screen

PS. tabulate simply convert the dataframe to decorated text for printing purposes

Edit: This is overkill but; to get the exact output, the index can be reset/renamed then to_csv parameter index is set to False; meaning the index is not to be stored enter image description here

Upvotes: 1

charlesreid1
charlesreid1

Reputation: 4841

Dictionaries with identical key sets

dict1 = {'a':100,'b':200,'c':300} 
dict2 = {'a':0.20,'b':0.25,'c':0.30}

with open('some_file','w') as f:
    f.write('Key\tValue1\tValue2\n')
    for k in sorted(dict1.keys()):
        f.write("{0}\t{1}\t{2}\n".format(k,dict1[k],dict2[k]))

This iterates over one key set, and prints out values from both dictionaries. (Bonus: works in both Python 2 and Python 3.)

Dictionaries with disjoint key sets

For anyone who was hoping to find an answer to the question where there are potentially multiple dictionaries, and potentially disjoint keysets, here's a (somewhat hacky) answer:

dict1 = {'a':100,'b':200,'c':300} 
dict2 = {'a':0.20,'b':0.25,'c':0.30,'d':0.40}
dict3 = {'a':2000,'b':2500,'d':9000,'e':9500}

with open('some_file','w') as f:
    f.write('Key\tValue1\tValue2\tValue3\n')
    keys_union = set(dict1.keys()).union(set(dict2.keys())).union(set(dict3.keys()))
    for k in sorted(keys_union):
        f.write("{0}\t{1}\t{2}\t{3}\n".format( k,
                        [dict1[k] if k in dict1.keys() else "-"][0],
                        [dict2[k] if k in dict2.keys() else "-"][0],
                        [dict3[k] if k in dict3.keys() else "-"][0]))

This prints a "-" for values that are missing from one of the dictionaries.

Upvotes: 1

Related Questions