WhyAyala
WhyAyala

Reputation: 675

Python function not returning correct output

Trying to use python to change the value associated to a key in a dictionary and it's not returning the correct output

def fetchAndReplace(dictionary,key,newValue):
    keys = dictionary.keys()
    for i in keys:
        if i == key:
            print dictionary[key]
            dictionary[key] = newValue
            return

        else: 
            return "Nothing"

When I call this one a dictionary {'x':3,'y':2}, with x for key and 6 for newValue It returns the string nothing, which it shouldn't. I can't find anything wrong with my code so if you could point out the mistake I'm overlooking I'd appreciate it.

Upvotes: 0

Views: 1554

Answers (5)

Echo_Mirage
Echo_Mirage

Reputation: 1

It seems like you wanted to plan in case of there not being a dictionary. However, you already created one. Take out the return nothing.

Upvotes: 0

aaronfay
aaronfay

Reputation: 1692

The problem is you are returning on the first iteration, so you never get to the second key.

Try this:

def fetchAndReplace(dictionary, key,newValue):
    keys = dictionary.keys()
    for i in keys:
        if i == key:
            dictionary[key] = newValue

    return dictionary



print fetchAndReplace({'x':3,'y':2}, 'x', 6)

Output:

{'y': 2, 'x': 6}

Furthermore, you can accomplish the same as your function with the dict.update method:

>>> mydict = {'x':3,'y':2}
>>> mydict.update({'x': 6})
>>> print mydict
{'y': 2, 'x': 6}

Hth,
Aaron

Upvotes: 3

justhalf
justhalf

Reputation: 9107

I'm so tempted to answer this.

You only need to delete two tab characters (or 8, if you use spaces) in order to make your code work.

Decrease the indentation of else: and return "Nothing"

Result:

def fetchAndReplace(dictionary, key, newValue):
    keys = dictionary.keys()
    for i in keys:
        if i == key:
            print dictionary[key]
            dictionary[key] = newValue
            return
    else:
        return "Nothing"

dictionary = {"x":1, "y":2}
print "The result is: " + str(fetchAndReplace(dictionary,"x",3))
print "The result is: " + str(fetchAndReplace(dictionary,"z",0))

This will produce:

1
The result is: None
The result is: Nothing

Why? Because by decreasing the indentation, the else will be attached to for, and according to this documentation, the else part in for..else will be executed only when the for loop exits normally (i.e., without break or return), which is why it will iterate over all entries, and only if the key is not found, it will return the string "Nothing". Otherwise it will return None, since you just have the statement return.

But as others had noticed, you would probably want something like this:

def fetchAndReplace(dictionary, key, newValue):
    result = dictionary.get(key, "Nothing")
    dictionary[key] = newValue
    return result

which logic is to save the original value of dictionary[key] in variable result, and if the key is not available, it will be assigned the value Nothing. Then you replace the value of that key with dictionary[key] = newValue, and then return the result.

Running this code:

dictionary = {"x":1, "y":2}
print "The result is: " + fetchAndReplace(dictionary,"x",3)
print "The result is: " + fetchAndReplace(dictionary,"z",0)

will produce

The result is: 1
The result is: Nothing

Upvotes: 0

wwii
wwii

Reputation: 23753

print statements always help

def fetchAndReplace(dictionary,key,newValue):
    keys = dictionary.keys()
    print 'keys:', keys
    for i in keys:
        print 'i:', i, 'i == key:', i == key
        if i == key:
            print dictionary[key]
            dictionary[key] = newValue
            return

        else: 
            return "Nothing"

Items in a dictionary are almost arbitrarily ordered, if the conditional statement if i == key fails with the first item in keys, the function will return

Upvotes: 0

dawg
dawg

Reputation: 103824

I think you are trying to do something along these lines:

def fetchAndReplace(dictionary,key,newValue):
    if key in dictionary:
        dictionary[key]=newValue
        return dictionary
    else:
        return 'Nothing' 

di=  {'x':3,'y':2}

print fetchAndReplace(di, 'z', 6)    
print fetchAndReplace(di, 'x', 6)

Prints:

Nothing
{'y': 2, 'x': 6}

Upvotes: 2

Related Questions