1

I'm trying to import a CSV file as a dictionary in python but with a set layout.

My code below works

CSV file

key1, value1
Key2, value2

Script

Import cvs
with open('test.csv', mode='r') as infile:

    with open('dict.py', mode='w') as outfile:
        mydict = {rows[0]:rows[1] for rows in reader}
        output.write(mydict)

So my output looks like

{'Key1': 'value1', 'Key2': 'value2'}

How can I make it look like

{
'Key1': 'value1', 
'Key2': 'value2',
}

Basically on a newline each?

P.s sorry about formatting done on mobile app

WraithNath
  • 17,658
  • 10
  • 55
  • 82
shaggs
  • 600
  • 7
  • 27
  • use [string formatting](https://docs.python.org/2/library/string.html#format-examples) – LinkBerest Oct 05 '15 at 23:01
  • Possible duplicate of [pretty printing nested dictionaries in Python?](http://stackoverflow.com/questions/3229419/pretty-printing-nested-dictionaries-in-python) – LinkBerest Oct 06 '15 at 01:34
  • No not a duplicate as im not wanting to indent nor use pretty print. – shaggs Oct 06 '15 at 02:05
  • 1
    If you read through the answers several [do not use pretty print](https://stackoverflow.com/questions/3229419/pretty-printing-nested-dictionaries-in-python/3314411#3314411) (the activestate one is almost a direct quote of what you are trying to do) and most of them include settings for indentation or lack thereof. – LinkBerest Oct 06 '15 at 02:40
  • Noted and shall re read – shaggs Oct 06 '15 at 02:47
  • Thanks @JGeenwell found one and used it. – shaggs Oct 06 '15 at 12:47

0 Answers0