Ad

How To Update A Dictionary Without Having To Create A New Dictionary?

- 1 answer

This problem specifies that a dictionary and a list of integers is passed into a function as parameters that is supposed to update the dictionary by removing the integer elements in the list values that are in the list of integers. In this case, the integer list [2, 5] is passed and compared with the dictionary values.

For example, given the dictionary:

1. {3: [3, 7, 4], 7: [6, 1, 2, 5, 5, 2], 2: [2, 1, 8, 0], 8: [-3, 9, 5]}

After update:

2. {3: [3, 7, 4], 7: [6, 1], 2: [1, 8, 0], 8: [-3, 9]}

Notice the list values have all the 2 and 5's removed as the integer list [2, 5] is one of the parameters.

If I don't return the dictionary, it returns None, but I can't directly return the original dictionary either as it returns the exact same dictionary with no integers removed. I also tried creating a new dictionary and used the items method to append everything again but with some integers removed, but that also did not return an updated dictionary.

The code:

def main():
    a_dict = {3: [3, 7, 4], 7: [6, 1, 2, 5, 5, 2], 2: [2, 1, 8, 0], 8: [-3, 9, 5]}
    print("1.", a_dict)
    updated = update_corresponding_values(a_dict, [2, 5])
    print("2.", updated)

def update_corresponding_values(a_dict, list1):
    for value in a_dict.items():
        if value in list1:
            del a_dict[value]

main()

Expected:

1. {3: [3, 7, 4], 7: [6, 1, 2, 5, 5, 2], 2: [2, 1, 8, 0], 8: [-3, 9, 5]}

2. {3: [3, 7, 4], 7: [6, 1], 2: [1, 8, 0], 8: [-3, 9]}

Got: (if I return something)

1. {3: [3, 7, 4], 7: [6, 1, 2, 5, 5, 2], 2: [2, 1, 8, 0], 8: [-3, 9, 5]}
2. {3: [3, 7, 4], 7: [6, 1, 2, 5, 5, 2], 2: [2, 1, 8, 0], 8: [-3, 9, 5]}
Ad

Answer

I think your update_corresponding_values function is incorrect in several ways. For example, updated should be None, given the function returns nothing, it just changes the a_dict object. Secondly, O don't think the if statement ever fires, because value is a tuple (key,value_list), so it's basically checking if key == [2,5] or value_list == [2,5].

Try:

def update_corresponding_values(a_dict, list1):
    for key in a_dict.keys():
        new_list = []
        for value in a_dict[key]:
            if value in list1:
                continue
            new_list.append(value)
        a_dict[key] = new_list
    return a_dict
Ad
source: stackoverflow.com
Ad