Updating a dictionary in python

I’ve been stuck on this question for quite sometime and just can’t figure it out. I just want to be able to understand what I’m missing and why it’s needed. What I need to do is make a function which adds each given key/value pair to the dictionary. The argument key_value_pairs will be a list of tuples in the form (key, value).

def add_to_dict(d, key_value_pairs):

    newinputs = [] #creates new list
    for key, value in key_value_pairs:
        d[key] = value #updates element of key with value
        if key in key_value_pairs:
            newinputs.append((d[key], value)) #adds d[key and value to list
    return newinputs

I can’t figure out how to update the “value” variable when d and key_value_pairs have different keys.

The first three of these scenarios work but the rest fail

>>> d = {}
>>> add_to_dict(d, [])
[]
>>> d
{}

>>> d = {}
>>> add_to_dict(d, [('a', 2])
[]
>>> d
{'a': 2}

>>> d = {'b': 4}
>>> add_to_dict(d, [('a', 2)])
[]
>>> d
{'a':2, 'b':4}

>>> d = {'a': 0}
>>> add_to_dict(d, [('a', 2)])
[('a', 0)]
>>> d
{'a':2}

>>> d = {'a', 0, 'b': 1}
>>> add_to_dict(d, [('a', 2), ('b': 4)])
[('a', 2), ('b': 1)]
>>> d
{'a': 2, 'b': 4}

>>> d = {'a': 0}
>>> add_to_dict(d, [('a', 1), ('a': 2)])
[('a', 0), ('a':1)]
>>> d
{'a': 2}

Thanks

Edited.

Leave a Comment