0

I am writing a function add_to_dict(d, key_value_pairs) which adds each given key/value pair to the given dictionary. The argument key_value_pairs will be a list of tuples in the form (key, value).

The function should return a list of all of the key/value pairs which have changed (with their original values).

def add_to_dict(d,key_value_pairs):
    key_value_pairs=()
    thelist=[]
    thelist.append(list(d))
    for key, value in key_value_pairs:
        d[value]=key
    thelist.append(list(key_value_pairs))
    return thelist

What I got here seems completely not right and I have no clue at the moment.

Bretsky
  • 423
  • 8
  • 23
Nil
  • 13
  • 2
  • 9
  • Are you aware that dictionaries have an `update` method which basically already does what you are trying to do? Except for returning the list of key/value pairs, but that's what the `items` method of the dictionary is for. – mkrieger1 Sep 04 '15 at 10:34
  • **See also:** https://stackoverflow.com/questions/1452995/why-doesnt-a-python-dict-update-return-the-object – dreftymac Jul 02 '18 at 23:18

1 Answers1

0

From what I understand, you want to add a list of key/value tuples to a dictionary. The function will return all of the key/value pairs that were changed. I commented the problems I found in your code.

def add_to_dict(d,key_value_pairs):
    key_value_pairs=() #This changes your list of key/value tuples into an empty tuple, which you probably don't want
    thelist=[]
    thelist.append(list(d)) #This appends all of the keys in d to thelist, but not the values
    for key, value in key_value_pairs:
        d[value]=key #You switched the keys and values
    thelist.append(list(key_value_pairs)) #This is already a list, so list() is unnecessary
    return thelist

I would suggest simply returning key_value_pairs as it already contains all of the keys and values that were modified. Let me know if you need more detail on how to fix the problems, but first try and figure it out yourself.

Bretsky
  • 423
  • 8
  • 23