I have two dictionaries for example:
dict1 = {1:[30], 2:[42]}
where the key is the product code and the values are the average sale
dict2 = {"apple":1, "banana":2}
where the key is the product name and values is the product key.
I want to write a CSV file so that I have:
| product name | product code | average sales |
|---|---|---|
| "apple" | 1 | 30 |
| "banana" | 2 | 42 |
What would be the best way to solve this problem?
This is a way how you can do it. I am sure there are better ways too.
import pandas as pd
dict2 = {"apple": 1, "banana": 2}
dict1 = {1: [30], 2: [42]}
df = pd.DataFrame(list(dict1.items()), columns=['product code','average sales'])
df['average sales'] = df['average sales'].str[0] #removing the square brackets
df2 = pd.DataFrame(list(dict2.items()), columns=['product name','xx'])
df3 = pd.concat([df,df2],axis=1).iloc[:, 0:3] #taking only the first 3 columns
print(df3)
df3.to_csv('file.csv', index=False)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With