Dictionary practice problem 4

I dont understand why my code is not working. it works when I click on run code and I get the expected answer as shown in the screen but upon clicking submit answer am told there an error " Function update did not correctly modify the value of argument number 1 ."

def update(dic,iterable):
    for pair in iterable:
        if pair[0] in dic:
            dic[pair[0]]+=pair[1]
        else:
            dic[pair[0]]=pair[1]
            
some_d = {"a":0, "d":3}
update(some_d, [("a", 97), ("b", 98), ("c", 99)])
print(some_d)

Hi!
The instructions say that the function should update the given dictionary with the values in the iterable if the key is in the dictionary. What you function does is to add the value in the iterable to the existing value. When you test it, you get the same results as expected because the only existing key is a and its value is 0, adding to zero gives 97 as well.

thanks I have identified the error you indicated.

def update(dic,iterable):
    for pair in iterable:
        a=pair[0]
        b=pair[1]
        if a in dic:
            dic[a]=b
        else:
            dic[a]=b
        
some_d = {"a":0, "d":3}
update(some_d, [("d", 97), ("b", 98), ("c", 99)])
print(some_d)
1 Like

Welcome!
Actually, the if-clause is redundant here: you assign the same action in case a is in the dictionary and in case it´s not. It´s due to the fact that updating a value and introducing a new value to a dictionary is done using the same syntax.

P.S.: I would also recommend you to check the solutions both in this module and the module on lists, as they introduce some interesting built-in methods for these objects which were not covered in the related courses. For example, for this function, you could use dict.update() method.

Thanks once again. I have understood what you meant by the if is redundant.

def update(dic,iterable):
    for pair in iterable:
        a=pair[0]
        b=pair[1]
        dic[a]=b 

About the other method, dict.update(), I saw it but refrained from using it because I didnt understand how the method for the dict class works behind the scene on my dictionary to perform the update.

the method I used helps me understand whats happening when I run the function.

Please any advise on which of these two methods, I should focus more on???
As its seems for most of the practice questions the cleaner and shorter methods like dict.update() are mostly used to solve the questions