Python Dictionary to CSV

Writing a dictionary to a csv file with one line for every 'key: value'

The DictWriter doesn't work the way you expect.

with open('dict.csv', 'w') as csv_file:  
writer = csv.writer(csv_file)
for key, value in mydict.items():
writer.writerow([key, value])

To read it back:

with open('dict.csv') as csv_file:
reader = csv.reader(csv_file)
mydict = dict(reader)

which is quite compact, but it assumes you don't need to do any type conversion when reading

Convert Python Dictionary To .csv file

You will have to munge your dict a bit, but something like this would work:

import csv

field_names = ['date', 'name']

my_dict={"date":['11/2/19','3/11/20'],"name":['dexter','morgan']}

with open('file.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(field_names)
rows = zip(*[my_dict[name] for name in field_names])
writer.writerows(rows)

This use of zip is a common idiom for "transposing", so:

zip(*[my_dict[name] for name in field_names])

So, for example:

In [2]: my_dict={"date":['11/2/19','3/11/20'],"name":['dexter','morgan']}

In [2]: field_names = ['date', 'name']

In [3]: list(zip(*[my_dict[name] for name in field_names]))
Out[3]: [('11/2/19', 'dexter'), ('3/11/20', 'morgan')]

Writing a Python Dictionary to CSV

You can import the dictionary to a pandas dataframe. This can then be exported as a csv without the column names to achieve what you require.

The following code snippet would do the trick:

import pandas as pd

df = pd.DataFrame.from_dict({(i,j): Inventory[i][j]
for i in Inventory.keys()
for j in Inventory[i].keys()},
orient='index')
df.to_csv('test.csv', header = False)

This is how your test.csv looks like for the dictionary called Inventory you have shown in the question:

devicename,Interface1,value,value
devicename,Interface2,value,value

How to convert a Dictionary to CSV file?

You've got to work a little on the data before writing it to CSV. You may want to create of list of dictionaries that represent your CSV rows before writing the CSV:

import csv
x = {'2020-09-03': {'1. open': '128.1900', '2. high': '129.9500', '3. low': '123.6500', '4. close': '124.4500', '5. volume': '5716750'},
'2020-09-02': {'1. open': '123.7200', '2. high': '129.9500', '3. low': '19.9500'}}
data = [] #list of data to be written
for k,v in x.items(): #iterate through rows of dictionary x
f = {} #dictionary to which all data gather for each iteration is held
f['date'] = k #get date
f['open'] = v['1. open'] #get open
f['high'] = v['2. high'] #get high
f['low'] = v['3. low'] #get low
data.append(f) # append dictionary f to data list

header = ['date', 'open', 'high', 'low'] #set CSV column headers

# open the csv file in write mode
file = open('arngcsv.csv', 'w', newline ='')
with file:
# identifying header
writer = csv.DictWriter(file, fieldnames = header)
# write data row-wise into the csv file
writer.writeheader()
for row in data:
writer.writerow(row)

Python convert dictionary to CSV

Using DictWriter from the csv module

Demo:

import csv

data_list ={'x':{'title':'productName()','price':'price()','description':'description()','preorder':'checkPreorder()',
'estimate delivery':'estimateDelivery()','variation': 'variation()', 'category':'categories()',
'brand':'brand()','image':'image_link()'}}

with open(filename, "w") as infile:
writer = csv.DictWriter(infile, fieldnames=data_list["x"].keys())
writer.writeheader()
writer.writerow(data_list["x"])

Reading/Writing out a dictionary to csv file in python

I didn't find enough benefit to use Pandas here since the problem is simple.

Also note to OP, if you want to store values to a file just for reading it back simply use JSON or Python's shelve module. Exporting to CSV should be minimised only when we need to interact potentially Excel users.

The below code converts a dict into CSV

value1 = 'one'
value2 = 'two'
d = {
'key1': (value1, value2),
'key2': (value1, value2),
'key3': (value1, value2)
}
CSV ="\n".join([k+','+','.join(v) for k,v in d.items()])
#You can store this CSV string variable to file as below
# with open("filename.csv", "w") as file:
# file.write(CSV)

This code explains what happens inside the list comprehension.

CSV = ""
for k,v in d.items():
line = "{},{}\n".format(k, ",".join(v))
CSV+=line
print CSV


Related Topics



Leave a reply



Submit