Write dictionary (keys and values) to a csv file - python

I just want the csv file to look like this:
key,item1,item2,item3
key2,itema,itemB,itemC
and so on
The dictionary has a key and the value is a list of floats.
This is the current code I have to write to the csv file but all it does is write out the key like this: k,e,y,s
Any help is appreciated
with open(outFileName1, 'w') as outfile:
csv_Writer = csv.writer(outfile)
csv_Writer.writerows(dict1)

import csv
dict_data = {'key1': [1, 2, 3], 'key2': [4, 5, 6]}
with open("dict2csv.txt", 'w') as outfile:
csv_writer = csv.writer(outfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
for k,v in dict_data.items():
csv_writer.writerow([k] + v)
This code will write each key, value pair in your desire format on separate line in csv file.

Without getting into details how CSV works you can easily solve it with something like:
with open("out.txt", 'w') as outfile:
for k,v in dict1.items():
outfile.write(str(k))
for item in v:
outfile.write(","+str(item))
outfile.write(" ")

Your current code iterates the dictionary which yields keys only. Take a look at
import csv
data = {
'key1': ['item1', 'item2'],
'key2': ['item3', 'item4']
}
with open('', 'w') as outfile:
writer = csv.writer(outfile)
for k, v in data.iteritems():
writer.writerow([k] + v)
Notice that it iterates key-value pairs returned by .iteritems(). The key is inserted into a list which is concatenated with the value list.

Related

How can I read from this file and turn it to a dictionary?

I've tried several methods to read from this file and turn it to a dictionary but I'm having a lot of errors
I've tried the following method but it did not work I got not enough values unpack.
d = {}
with open("file.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
I want to read and convert it to this:
{123: ['Ahmed Rashed', 'a', '1000.0'], 456: ['Noof Khaled', 'c', '0.0'], 777: ['Ali Mahmood', 'a', '4500.0']}
Split on commas instead.
d = {}
with open("file.txt") as f:
for line in f:
parts = line.rstrip('\n').split(',')
d[int(parts[0])] = parts[1:]
Using csv.reader to read the file and split it into its fields:
import csv
with open("file.txt") as f:
d = {
int(num): data
for num, *data in csv.reader(f)
}

List to dictionary - improvement?

The following code does what I want, but any other way more python-style of doing it?
Having file in the format:
key1:value1,key2:value2,...
key21:value21,key22:value22,...
.
EOF
and code:
file = open(fileName, 'r')
for lines in file:
line = lines.split(",")
my_dict = {}
for item in line:
key_value = item.split(":")
my_dict.update({key_value[0]:key_value[1]})
Thanks
A faster & more pythonic way would be to use csv module (comma separated by default) and split items in a double flattened generator comprehension fed to dict that accepts tuples with 2 elements:
import csv
with open("test.csv",newline="") as f: # replace ,newline="" by ,"rb" in python 2
cr = csv.reader(f)
d = dict(x.split(":") for row in cr for x in row)
print(d)
result:
{'key1': 'value1', 'key22': 'value22', 'key21': 'value21', 'key2': 'value2'}
non-csv version:
import csv
with open("test.csv") as f:
d = dict(x.split(":") for line in f for x in line.split(","))
Using split():
list.txt:
key1:value1,key2:value2,key3:value3
key21:value21,key22:value22
Hence:
with open("list.txt") as fileObj:
content = fileObj.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
for line in content:
for elem in line.split(","):
print({elem .split(":")[0] : elem.split(":")[1]})
OUTPUT:
{'key1': 'value1'}
{'key2': 'value2'}
{'key3': 'value3'}
{'key21': 'value21'}
{'key22': 'value22'}
OR
If you want them stored in the dict:
for line in content:
for x in line.split(","):
dict_.update({x.split(":")[0] : x.split(":")[1]})
print(dict_['key1']) # value1

How to create a dictionary from a txt file on Python

This is the txt file content I have:
salesUnits:500
priceUnit:11
fixedCosts:2500
variableCostUnit:2
I need to create a dictionary in Python that will read the file and make the keys the salesUnits etc. and the values the numbers. The code I have so far will only print the variable cost per unit:
with open("myInputFile.txt") as f:
content = f.readlines()
myDict = {}
for line in content:
myDict=line.rstrip('\n').split(":")
print(myDict)
How can I fix the code so that all key and value pairs show up? Thank you!
You're overwriting myDict each time you call myDict=line.rstrip('\n').split(":"). The pattern to add to a dictionary is dictionary[key] = value.
myDict = {}
with open("myInputFile.txt") as f:
for line in f:
key_value = line.rstrip('\n').split(":")
if len(key_value) == 2:
myDict[key_value[0]]=key_value[1]
print(myDict)
outputs
{'fixedCosts': '2500', 'priceUnit': '11', 'variableCostUnit': '2', 'salesUnits': '500'}
Using a simple dict comprehension will handle this:
with open('testinput.txt', 'r') as infile:
dict = {
line.strip().split(':')[0]:
int(line.strip().split(':')[1])
if line.strip().split(':')[1].isdigit()
else
line.strip().split(':')[1]
for line in infile.readlines()}
print(dict)
Output:
{'salesUnits': 500, 'priceUnit': 11, 'fixedCosts': 2500, 'variableCostUnit': 2}
If you wish to bring the numbers in as simple strings, just use:
dict = {
line.strip().split(':')[0]:
line.strip().split(':')[1]
for line in infile.readlines()}
Note also that you can add handling for other data types or data formatting using additional variations of:
int(line.strip().split(':')[1])
if line.strip().split(':')[1].isdigit()
else
myDict = {}
with open('dict.txt', 'r') as file:
for line in file:
key, value = line.strip().split(':')
myDict[key] = value
print myDict
Output:
{'fixedCosts': '2500', 'priceUnit': '11', 'variableCostUnit': '2', 'salesUnits': '500'}

Creating dictionary from CSV file, dictionary not containing all values

For the following CSV File:
A,B,C
-----
A1,B1,C1
A1,B2,C2
A2,B3,C3
A2,B4,C4
My dictionary currently looks like this:
{'A1': {'B':'B1', 'C':'C1'}, 'A2': {'B':'B3', 'C':'C3'}
How do I get my dictionary to look like this:
'A1': {'B': ['B1', 'B2'], 'C': ['C1', 'C2']}, 'A2': {'B': ['B3', 'B4'], 'C': ['C3', 'C4']}}
I'm using the following code at the moment:
import csv
reader = csv.DictReader(open('test.csv'))
result = {}
for row in reader:
key = row.pop('A')
if key in result: pass
result[key] = row
print result
You need to create a base case for each key, such that the dictionary inserts the first value as a list. Then you can append values for duplicate keys as they are encountered.
The following code should do what you need:
with open('test.csv') as f:
reader = csv.DictReader(f)
for row in reader:
key = row.pop('A')
if '-' in key:
continue
if key not in result:
new_row = {'B': [row.pop('B')], 'C': [row.pop('C')]}
result[key] = new_row
else:
result[key]['B'].append(row.pop('B'))
result[key]['C'].append(row.pop('C'))
You don't have to use DictReader to achieve this. You can just use regular csv.reader and fill up your own dictionary.
Here is a commented simple solution:
from __future__ import print_function
import csv
csv_fpath = 'test.csv'
# readcsv.py
# You want this:
#{'A1': {'B':['B1','B2'], 'C':['C1','C2']}, 'A2': {'B':['B3','B4'], ..}}
mydict = {}
# newline = '' option is needed as per csv.reader documentation python 3.x
with open(csv_fpath, mode='r') as csvfile:
# A regular csv reader object
myreader = csv.reader(csvfile, delimiter=',')
# Header on first line
hrow = next(myreader)
# # Tagging header names for dictionary keys later
taga, tagb, tagc = hrow[0], hrow[1], hrow[2]
# Skip separator line (delete this line if unnecessary)
next(myreader)
# Reading data and constructing our dictionary
for row in myreader:
if len(row) == 0:
# ignore blank lines
continue
# Each row's key is the first column value
key = row[0]
if key in mydict:
# If an item exists with the given key, that item itself is also a
# dictionary with lists in keys tagb and tagc. So we append to those
# lists the values in second and third columns
mydict[key][tagb].append(row[1])
mydict[key][tagc].append(row[2])
else:
# Note the list constructors, they are important as we are going to
# append them down the iteration
mydict[key] = { tagb: [row[1]]
, tagc: [row[2]]}
print(mydict)
Slightly different approach:
reader = csv.DictReader(open("test.csv"))
result = {}
for row in reader:
if reader.line_num <= 2:
continue
key = row["A"]
for subkey in [k for k in row.keys() if k != "A"]:
if key not in result:
result[key] = {}
if subkey not in result[key]:
result[key][subkey] = []
result[key][subkey].append(row[subkey])
>>> print(result)
{'A2': {'C': ['C3', 'C4'], 'B': ['B3', 'B4']}, 'A1': {'C': ['C1', 'C2'], 'B': ['B1', 'B2']}}

How to turn CSV data into dictionary [duplicate]

This question already has answers here:
Convert .csv table to dictionary [duplicate]
(4 answers)
Closed 9 years ago.
I have a CSV file which I am opening through this code:
open(file,"r")
When I read the file I get the output:
['hello', 'hi', 'bye']
['jelly', 'belly', 'heli']
['red', 'black', 'blue']
I want the otput something like this:
{hello:['jelly','red'], hi:['belly','black'], 'bye':['heli','blue']}
but I have no idea how
You can use collections.defaultdict and csv.DictReader:
>>> import csv
>>> from collections import defaultdict
>>> with open('abc.csv') as f:
reader = csv.DictReader(f)
d = defaultdict(list)
for row in reader:
for k, v in row.items():
d[k].append(v)
...
>>> d
defaultdict(<type 'list'>,
{'hi': ['belly', 'black'],
'bye': ['heli', 'blue'],
'hello': ['jelly', 'red']})
csv = [
['hello', 'hi', 'bye'],
['jelly', 'belly', 'heli'],
['red', 'black', 'blue'],
]
csv = zip(*csv)
result = {}
for row in csv:
result[row[0]] = row[1:]
yourHash = {}
with open(yourFile, 'r') as inFile:
for line in inFile:
line = line.rstrip().split(',')
yourHash[line[0]] = line[1:]
This assumes that each key is unique to one line. If not, this would have to be modified to:
yourHash = {}
with open(yourFile, 'r') as inFile:
for line in inFile:
line = line.rstrip().split(',')
if line[0] in yourHash:
yourHash[line[0]] += line[1:]
else:
yourHash[line[0]] = line[1:]
Of course, you can use csv, but I figured that someone would definitely post that, so I gave an alternative way to do it. Good luck!
You can use csv, read the first line to get the header, create the number of lists corresponding to the header and then create the dict:
import csv
with open(ur_csv) as fin:
reader=csv.reader(fin, quotechar="'", skipinitialspace=True)
header=[[head] for head in next(reader)]
for row in reader:
for i, e in enumerate(row):
header[i].append(e)
data={l[0]:l[1:] for l in header}
print(data)
# {'hi': ['belly', 'black'], 'bye': ['heli', 'blue'], 'hello': ['jelly', 'red']}
If you want something more terse, you can use Jon Clements excellent solution:
with open(ur_csv) as fin:
csvin = csv.reader(fin, quotechar="'", skipinitialspace=True)
header = next(csvin, [])
data=dict(zip(header, zip(*csvin)))
# {'bye': ('heli', 'blue'), 'hello': ('jelly', 'red'), 'hi': ('belly', 'black')}
But that will produce a dictionary of tuples if that matters...
And if you csv file is huge, you may want to rewrite this to generate a dictionary row by row (similar to DictReader):
import csv
def key_gen(fn):
with open(fn) as fin:
reader=csv.reader(fin, quotechar="'", skipinitialspace=True)
header=next(reader, [])
for row in reader:
yield dict(zip(header, row))
for e in key_gen(ur_csv):
print(e)
# {'hi': 'belly', 'bye': 'heli', 'hello': 'jelly'}
{'hi': 'black', 'bye': 'blue', 'hello': 'red'} etc...

Categories