Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing \n in dictionary

I've got a problem with removing \n in my program here is the code

with open(filename) as f:
    for line in f.readlines():
        parent, child = line.split(",")
            parent.strip()
            child.strip()
            children[child].append(parent)

tried using .rstrip and other variants but it does nothing for my, this is the result i get

{'Patricia\n': ['Mary'], 'Lisa\n': ['Mary']} 

the problem is when i call children["Patricia"] i get [], because it recognizes only children["Patricia\n"]

like image 926
D. K. Avatar asked Nov 27 '18 14:11

D. K.


People also ask

How to delete key value pair in 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.

How to remove a key in python dictionary?

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.


2 Answers

Actually, you were quite close. Strings are immutable and hence calling strip() will return a new string while leaving the original one intact.

So replacing

parent.strip()
child.strip()

with

parent = parent.strip()
child = child.strip()

would do the trick.

like image 131
Dušan Maďar Avatar answered Sep 23 '22 19:09

Dušan Maďar


Please use strip before split:

parent, child = line.rstrip("\n").split(",")

Issue was: parent.strip() needs to be re-assigned to a string as strings are immutable.

like image 32
Mayank Porwal Avatar answered Sep 25 '22 19:09

Mayank Porwal