Syed Abdul Qadeer
Syed Abdul Qadeer

Reputation: 465

CSV to dict, dict not finding the item

I am converting a CSV to dict, all the values are loaded correctly but with one issue.

CSV :

Testing    testing\nwe are into testing mode
My\nServer This is my server.

When I convert the CSV to dict and if I try to use dict.get() method it is returning None.

When I debug, I get the following output:

{'Testing': 'testing\\nwe are into testing mode', 'My\\nServer': 'This is my server.'}

The My\nServer key is having an extra backslash.

If I do .get("My\nServer"), I am getting the output as None.

Can anyone help me?

#!/usr/bin/env python

import os
import codecs
import json
from csv import reader

def get_dict(path):
    with codecs.open(path, 'r', 'utf-8') as msgfile:
        data = msgfile.read()
        data = reader([r.encode('utf-8') for r in data.splitlines()])
        newdata = []
        for row in data:
            newrow = []
            for val in row:
                newrow.append(unicode(val, 'utf-8'))
            newdata.append(newrow)
    return dict(newdata)

thanks

Upvotes: 1

Views: 104

Answers (2)

famousgarkin
famousgarkin

Reputation: 14126

You either need to escape the newline properly, using \\n:

>>> d = {'Testing': 'testing\\nwe are into testing mode', 'My\\nServer': 'This is my server.'}
>>> d.get('My\\nServer')
'This is my server.'

or you can use a raw string literal which doesn't need extra escaping:

>>> d.get(r'My\nServer')
'This is my server.'

Note that raw string will treat all the backslash escape sequences this way, not just the newline \n.

In case you are getting the values dynamically, you can use str.encode with string_escape or unicode_escape encoding:

>>> k = 'My\nServer' # API call result
>>> k.encode('string_escape')
'My\\nServer'
>>> d.get(k.encode('string_escape'))
'This is my server.'

Upvotes: 2

Jan Vlcinsky
Jan Vlcinsky

Reputation: 44132

"\n" is newline.

If you want to represent a text like "---\n---" in Python, and not having there newline, you have to escape it.

The way you write it in code and how it gets printed differs, in code, you will have to write "\" (unless u use raw string), when printed, the extra slash will not be seen

So in your code, you shall ask:

>>> dct = {'Testing': 'testing\\nwe are into testing mode', 'My\\nServer': 'This is my server.'}
>>> dct.get("My\\nServer")
'This is my server.'

Upvotes: 0

Related Questions