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