CodeTalk
CodeTalk

Reputation: 3667

Adding items to dictionary if condition is true, else dont - python

I'm trying to take an existing process:

if self.path_object is not None:
    dictpath = {}
    for path in self.path_object:
        self.params = path.pathval.split("?")[0]
        self.params = path.pathval.split("&", 2)
        if any(item in path.pathval for item in self.params):
            out = list(map(lambda v: v.split("=")[0] +"=" + str(self.fuzz_vectors), self.params))
            dictpath[path] = out
    print dictpath

Update For those finding this who looking for help with split() method . I've found it easier to do it with the urlparse library. Thanks to user DarinDouglass for pointing this out.

Thanks

Upvotes: 0

Views: 122

Answers (1)

BeetDemGuise
BeetDemGuise

Reputation: 974

Its because you are assigning the path to dictpath no matter what. The assignment will run EVERY iteration of the for loop.

To fix this you can either change pass to continue or move dictpath[path] = out into the true block of your if statement. The latter is the better option because you can then remove the else statement.


EDIT: Another problem is happening in your if statement. Let's break it down. What your conditional says is this:

  • Is there any item in self.params that can be found in path.pathval.

The problem with this is that this will ALWAYS be True because self.params is a sub-set of path.pathval; that is, you create self.params from path.pathval.

Here is a example to show what I mean:

pathval = 'www.example.com/some_path/?param1=1&param2=2'

# params = ['www.example.com/some_path/?param1=1', 'param2=2']
params = pathval.split('&', 2)

# Essentially says: is the string 'www.example.com/some_path...' in pathval? YES
if any(item in pathval for item in params)
    # Add to dict

Once your code is fixed, feel free to post it to Code Review as I have some statements that are more applicable there.

Upvotes: 1

Related Questions