Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over a dictionary in python and stripping white space

I am working with the web scraping framework Scrapy and I am wondering how do I iterate over all of the scraped items which seem to be in a dictionary and strip the white space from each one.

Here is the code I have been playing with in my item pipeline:

for info in item:
   info[info].lstrip()

But this code does not work, because I cannot select items individually. So I tried to do this:

for key, value item.items():
   value[1].lstrip()

This second method works to a degree, but the problem is that I have no idea how then to loop over all of the values.

I know this is probably such an easy fix, but I cannot seem to find it.

like image 204
AlexW.H.B. Avatar asked Jan 18 '12 09:01

AlexW.H.B.


People also ask

How do you strip a dictionary in Python?

To remove a key from a dictionary in Python, use the pop() method or the “del” keyword.

How do you remove spaces from a dictionary?

Let's see how to remove spaces from dictionary keys in Python. Method #1: Using translate() function here we visit each key one by one and remove space with the none. Here translate function takes parameter 32, none where 32 is ASCII value of space ' ' and replaces it with none.

How do you delete something from the dictionary while iterating?

First, you need to convert the dictionary keys to a list using the list(dict. keys()) method. During each iteration, you can check if the value of a key is equal to the desired value. If it is True , you can issue the del statement to delete the key.

Can I use Clear () method to delete the dictionary?

Python Dictionary clear() MethodThe clear() method removes all the elements from a dictionary.


2 Answers

In a dictionary comprehension (available in Python >=2.7):

clean_d = { k:v.strip() for k, v in d.iteritems()}

Python 3.X:

clean_d = { k:v.strip() for k, v in d.items()}
like image 128
monkut Avatar answered Nov 15 '22 09:11

monkut


Not a direct answer to the question, but I would suggest you look at Item Loaders and input/output processors. A lot of your cleanup can be take care of here.

An example which strips each entry would be:

class ItemLoader(ItemLoader):

    default_output_processor = MapCompose(unicode.strip)
like image 29
zsquare Avatar answered Nov 15 '22 08:11

zsquare