Flodude
Flodude

Reputation: 275

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

Upvotes: 5

Views: 104

Answers (3)

Shubham Sharma
Shubham Sharma

Reputation: 71707

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

Upvotes: 4

Salvatore Calcagno
Salvatore Calcagno

Reputation: 145

First of all you should create a dictionary outside the function, add items in loop and write only at the end. With your code you're writing 3 times the same file and you see only the last row.

For index you should set index=True.

Here the code. Hope I help you!

import pandas as pd
import random

my_dict = {
    'key1':[],
    'key2':[],
    'key3':[]
}

def AddToDict(li):
    my_dict['key1'].append(random.randrange(1, li))
    my_dict['key2'].append(random.randrange(1, li))
    my_dict['key3'].append(random.randrange(1, li))

mylist = [10, 20, 30]
for li in mylist:
    AddToDict(li)

df = pd.DataFrame(my_dict)  # Here
df.to_csv('test.csv', index=True)

Upvotes: 0

IoaTzimas
IoaTzimas

Reputation: 10624

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

Upvotes: 2

Related Questions