Assume mydict
is unique based on each list item:
mylist = ['li1', 'li2']
mydict = {'key1': 'value1','key2': 'value2','key3': 'value3}
I want to write this stracture in a CSV
file:
ListItem, key1, key2, key3
li1, value1, value2, value3
li2, value1, value2, value3
This is a sample of how I try to do this; but my code overwrites the first line with each iteration, and I do not know how to write the list item in the first column. Could you give me a hand, please?
import pandas as pd
import random
def CreateDict(li):
dict = {}
dict['x'] = random.randrange(1, li) #25
dict['y'] = random.randrange(1, li) #27
print(dict)
return dict
mylist = [10, 20, 30]
for li in mylist:
mydict = CreateDict(li)
df = pd.DataFrame([mydict])
df.to_csv('test.csv', index=False)
I get this as an output:
x,y
25,27
Let's try dict.fromkeys
to generate data dictionary, then create a dataframe from this data
dictionary and use DataFrame.to_csv
to save as a csv
file:
data = dict.fromkeys(mylist, mydict)
pd.DataFrame(data).T.rename_axis('ListItem').to_csv('foo.csv')
EDIT: If you would like to create unique dictionary per item in mylist
you can use:
data = {li:CreateDict(li) for li in mylist}
pd.DataFrame(data).T.rename_axis('ListItem').to_csv('foo.csv')
# foo.csv
ListItem,key1,key2,key3
li1,value1,value2,value3
li2,value1,value2,value3
Working on your existing solution:
import pandas as pd
import random
def CreateDict(li):
dict = {}
dict['x'] = random.randrange(1, li) #25
dict['y'] = random.randrange(1, li) #27
print(dict)
return dict
mylist = [10, 20, 30]
df=pd.DataFrame(columns=['x', 'y'])
for li in mylist:
mydict = CreateDict(li)
df=pd.concat([df, pd.DataFrame([mydict])])
df['mylist']=mylist
result=df[['mylist', 'x', 'y']]
result.to_csv('test.csv', index=False)
Output:
mylist x y
10 6 3
20 8 2
30 7 4
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