python - How to get just str values into csv using DictWriter with multiple values per row -
i've generated dict of dicts, each containing 5 randomly generated string elements.
i'm trying output each dict single row in csv file, "clean" string value, without quotes or brackets.
starting this:
numberofhands = range(int(raw_input("# of hands want generate: "))) allhands = {} #create place hand dicts go in numberofhands: # loads allhands specified # of 5 card hands temphand = makehand(battlepile) allhands.update({i:temphand}) open(nameoffile,'wb') outfile: #makes csv using writer , list of dict values writer = csv.writer(outfile,delimiter='\t') key, value in allhands.items(): arow = [] in value: arow.append(value[i]) writer.writerow([arow])
the output looks this:
['spider' 'spaceship' 'evil' 'porcupine' 'sword']
['train' 'sumo wrestler' 'saw' 'glass' 'robot']
['bees' 'cannon' 'house' 't.n.t' 'sumo wrestler']
['air' 'spider' 'wind' 'spaceship' 'spicy']
['turtle' 'santa claus' 'car' 'airplane' 'cloud']
my goal output looks this:
spider spaceship evil porcupine sword
train sumo wrestler saw glass robot
bees cannon house t.n.t sumo wrestler
air spider wind spaceship spicy
turtle santa claus car airplane cloud
i'm struggling dictwriter - there cleaner, pythonic way achieve this? here's currently:
with open(nameoffile, 'wb') outfile: #makes csv using dictwriter , list of dict values fieldnames = [1,2,3,4,5] writer = csv.dictwriter(outfile, dialect='excel', fieldnames=fieldnames) key, value in allhands.items(): writer.writeheader() k, v in value[key]: writer.writerow([v])
which gives keyerror: 0
i appreciate guidance.
here example how write dict csv file via dictwriter.
i hoop helps.
import csv allhands = {1:'spider', 2:'spaceship', 3:'evil', 4:'porcupine', 5:'sword'} nameoffile ='e://file.csv' open(nameoffile, 'wb') outfile: #makes csv using dictwriter fieldnames = [1,2,3,4,5] writer = csv.dictwriter(outfile, dialect='excel', fieldnames=fieldnames) writer.writeheader() temp = dict() keys, values in allhands.items(): temp[keys] = values writer.writerow(temp)
Comments
Post a Comment