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?
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.
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.
Use str. strip() to remove newline characters from a list.
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(",")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With