Updating a pandas dataframe or csv with dictionary

csv, dictionary, python

Solution

The pandas append function takes care of most of this work for you. This code:

import pandas as pd

df = pd.DataFrame({'Apple': 10, "Mango": 20, "Banana": 30}, index=['John'])

jen = pd.Series({"Apple": 10, "Banana": 30, "Watermelon": 5}, name='Jen')
df = df.append(jen)

print(df)

yields this result:

      Apple  Banana  Mango  Watermelon
John   10.0    30.0   20.0         NaN
Jen    10.0    30.0    NaN         5.0

If you want to move it to csv from there you can tack `df.to_csv(csv_filepath)` on the end of the program and it'll export it to the filepath you specified.

Problem

A function in my script returns a dictionary for `John` as follows: ``` { "Apple": 10, "Mango": 20, "Banana":30} ``` The keys and values are not necessarily the same every time I call the function. For example, it can also yield a dictionary for `Jen` such as ``` { "Apple": 10, "Banana":30, "Watermelon": 5} ``` I want to update the values to preferably a csv (or to a pandas dataframe and then to csv) to store it for later analysis. The desired output of the csv is: ``` Name | Apple | Banana | Mango | Watermelon | ------------------------------------------ John | 10 | 30 | 20 | Jen | 10 | 30 | | 5 ``` So, the puedocode is as follows: ``` if dictionary-keys == csv_or_df_header: add value to corresponding columns by matching keys with column headers else: add the new key as a column header add value to corresponding columns by matching keys with column headers ```

Original source