Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove \n from my python dictionary?

So I have a text file that is something like:

apples,green
tomatos,red
bananas,yellow

and my code to use this as a dictionary is

def load_list(filename):
    with open(filename, "rU") as my_file:
        my_list = {}
        for line in my_file:
            x = line.split(",")
            key = x[0]
            value = x[1]
            my_list[key] = value
        print my_list

which works fine, except that every value has \n added to the end of it, because of the line break. I tried adding

.strip()

to the x attribute, but it reulsted in an attribute error (AttributeError: 'dict' object has no attribute 'strip').

So how do I remove the \n?

like image 419
Chrystael Avatar asked Apr 06 '14 06:04

Chrystael


People also ask

Can you remove a key from a dictionary Python?

To remove a key from a dictionary in Python, use the pop() method or the “del” keyword. Both methods work the same in that they remove keys from a dictionary. The pop() method accepts a key name as argument whereas “del” accepts a dictionary item after the del keyword.

How do you remove a key value pair from a dictionary?

To delete a key, value pair in a dictionary, you can use the del method. A disadvantage is that it gives KeyError if you try to delete a nonexistent key. So, instead of the del statement you can use the pop method. This method takes in the key as the parameter.

How do you remove n from a list in Python?

Use str. strip() to remove newline characters from a list.


1 Answers

You should strip before splitting, like this

x = line.rstrip("\n").split(",")

we use str.rstrip here, because we just need to eliminate the newlines at the end of the line.

Also, you can unpack the key and values straight away, like this

key, value = line.rstrip("\n").split(",")
like image 106
thefourtheye Avatar answered Oct 01 '22 18:10

thefourtheye