Reputation: 171
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?
Upvotes: 3
Views: 102
Reputation: 5597
You could iterate through the keys of dict2, to build each row by using
pd.DataFrame({'product name': k, 'product code': dict2[k], 'average sales': dict1[dict2[k]]})
and append it row by row to the df. The solution code is
import pandas as pd
dict1 = {1:[30], 2:[42]}
dict2 = {"apple":1, "banana":2}
df = pd.DataFrame() #empty df
for k in dict2:
df = df.append(pd.DataFrame({'product name': k,
'product code': dict2[k],
'average sales': dict1[dict2[k]] }))
df.to_csv('my_file.csv', index=False)
Upvotes: 0
Reputation: 10789
There are a few ways to do this correctly. I think the following is quite instructive, especially if you aren't too familiar with Pandas.
d1 = {1:[30], 2:[42]}
d2 = {"apple":1, "banana":2}
def get_key(d, val):
'''return key for any value'''
for k, v in d.items():
if val == v:
return k
return "key doesn't exist"
#Make a new dict containing all the columns you need
r = {'product name':[], 'product code':[], 'average sales':[]}
#Populate r
for k,v in d1.items():
r['product code'].append(k)
r['average sales'].append(*v) #* unpacks the list item
r['product name'].append(get_key(d2, k))
#Make a DataFrame and export it
import pandas as pd
df = pd.DataFrame(r)
df.to_csv('your_file.csv', index=False)
Upvotes: 0
Reputation: 480
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)
Upvotes: 2
Reputation: 80
import csv
dict1 = {1:[30], 2:[42]}
dict2 = {"apple":1, "banana":2}
# Final array, will be written to csv
data = []
for name, code in dict2:
if code in dict:
avg_sales = dict1[code][0]
data += [name, code, avg_sales]
# else key doesn't exist
with open('myfile.csv', 'w', newline='') as file:
mywriter = csv.writer(file, delimiter=',')
mywriter.writerow(["Product Name", "Product Code", "Average Sales"]) # Headers
mywriter.writerows(data) # Data
Btw, it looks like your values in dict1 are single element arrays, so I'm using dict1[code][0]
. If you change it to just integer values, it'll just be dict1[code]
.
Upvotes: 0
Reputation: 5479
You can merge the dictionaries, then convert to pandas dataframe, and then write the dataframe to csv:
import pandas as pd
dict1 = {1:[30], 2:[42]}
dict2 = {"apple":1, "banana":2}
#merge dict1 and dict2 into dict3:
dict3 = {k: [v, dict1[v][0]] for k, v in dict2.items()}
#create pandas dataframe from dict3 and transpose it.
df = pd.DataFrame(dict3).transpose()
#wite dataframe to csv file
df.to_csv("new_file.csv", header=None)
Here is the resulting new_file.csv:
apple,1,30
banana,2,42
Upvotes: 0