Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing data from a Python List and a Dictionary to CSV

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
like image 253
Flodude Avatar asked Jan 30 '21 10:01

Flodude


2 Answers

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
like image 157
Shubham Sharma Avatar answered Oct 31 '22 06:10

Shubham Sharma


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
like image 39
IoaTzimas Avatar answered Oct 31 '22 06:10

IoaTzimas