0

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.

5
  • 3
    Do you understand what for does? Commented Oct 2, 2013 at 2:45
  • 1
    Once you return "Nothing" on the first i in the for loop, the loop and the function end. Commented Oct 2, 2013 at 2:45
  • 4
    What is wrong with dictionary['x']=6? Commented Oct 2, 2013 at 2:49
  • here, i in for is not the index; rather it is the element; means, i is actually the key Commented Oct 2, 2013 at 2:49
  • You can decrease the indentation of else: and return "Nothing", and it will work as you would expect. =) Commented Oct 2, 2013 at 4:48

5 Answers 5

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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}

1 Comment

This is closer to what I was looking for. Good call on getting rid of the for loop. I was helping a friend with his homework, and it had already been a long day so this was just going over my head for some reason. It's very obvious now though. Thanks.
0

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

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.