Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using multiple dictionaries to write a csv file in python

Tags:

python

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?

like image 280
jean10 Avatar asked Dec 20 '25 20:12

jean10


1 Answers

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)
like image 101
TSnake Avatar answered Dec 23 '25 08:12

TSnake