How to Write a Python Dictionary to a CSV File

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

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

Creating a dictionary from a csv file?

I believe the syntax you were looking for is as follows:

import csv

with open('coors.csv', mode='r') as infile:
reader = csv.reader(infile)
with open('coors_new.csv', mode='w') as outfile:
writer = csv.writer(outfile)
mydict = {rows[0]:rows[1] for rows in reader}

Alternately, for python <= 2.7.1, you want:

mydict = dict((rows[0],rows[1]) for rows in reader)

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')]

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

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)

correctly write a dictionary into a csv python file by columns

You have created a normal CSV writer, but are trying to convert your data into a dictionary and write that. You could make use of a dictionary writer, but I feel it would make more sense to avoid trying to use a dictionary for this and to just convert your data into correctly formatted lists.

Currently you are building all the data in columns, but will need to write this in row form. Row/Col swapping can be done using zip(*[col1, col2, col3]). Also it would make sense to encode your data as you go along:

import requests
from bs4 import BeautifulSoup
import csv
import re

def get_html(url):
r = requests.get(url)
return r.text

url = 'http://www.autobody.ru/kuzovnoy-remont/'
html = get_html(url)
soup = BeautifulSoup(html, 'html.parser')
mydivs = soup.findAll('a',class_="banners_images")
urls = []

for i in mydivs:
ur = (i.get('href'))
ur = 'http://www.autobody.ru' + str(ur)
urls.append(ur)

images = []
heads = []
artic = []
atrib = []
price = []

with open('121.csv', 'wb') as f: # Open the file in binary mode for Python 2.x
f.write(u'\ufeff'.encode('utf8')) # writes "byte order mark" UTF-8 signature
writer = csv.writer(f)

for i in urls:
html = get_html(i)
soup = BeautifulSoup(html, 'html.parser')
head = soup.find('h1').get_text()
heads.append(head.encode('utf8'))

image = [x['src'] for x in soup.findAll('img', {'class': 'detimg'})]
image1 = 'http://www.autobody.ru'+image[0]
images.append(image1.encode('utf8'))

price1 = soup.find('div', class_='price').get_text()
price1 = re.sub(r"c",r"p", price1)
price.append(price1.encode('utf8'))

for tr in soup.find('table', class_='tech').find_all('tr'):
artic.append(tr.get_text().strip().encode('utf8'))

writer.writerows(zip(*[heads, price, artic, images]))

This would give you an output file starting:

CIVIC РУЧКА ПЕРЕД ДВЕРИ ЛЕВ ВНЕШН ЧЕРН,295 p,"Артикул
HDCVC96-500B-L",http://www.autobody.ru/upload/images/HDCVC96-500B-L.jpg.pagespeed.ce.JnqIICpcSq.jpg
CIVIC РУЧКА ПЕРЕД ДВЕРИ ЛЕВ ВНЕШН ЧЕРН,295 p,"Артикул
HDCVC96-500B-L",http://www.autobody.ru/upload/images/HDCVC96-500B-L.jpg.pagespeed.ce.JnqIICpcSq.jpg
AUDI A4 БАМПЕР ПЕРЕДН ГРУНТ,3882 p,"ОЕМ#
72180S04003",http://www.autobody.ru/upload/images/AI0A401-160X.jpg.pagespeed.ce.onSZWY1J15.jpg


Related Topics



Leave a reply



Submit