I am trying to add/append test_dict2 to test_dict, according to the below rules:
- If the
test_dict2dictionary key already exists intest_dict, updatetest_dict[key]with only new values fromtest_dict2[key] - If the dictionary key does not already exist in
test_dict, add the key and value.
Example:
test_dict = {'s': [1, 2], 't': 2}
test_dict2 = {'s': [1, 2, 3, 'yoyoyo'], 't': 2, 'u': [3, 4]}
After my intended update, test_dict should look like this:
test_dict = {'s': [1, 2, 3, 'yoyoyo'], 't': [2], 'u': [3, 4]}
I have working code, but it seems so inefficient:
def convert_values_to_list(value):
if isinstance(value, list) == False:
value = [value]
return value
for key, values in test_dict2.items():
values = convert_values_to_list(values)
print(key)
print(values)
if key not in test_dict:
test_dict[key] = values
else:
test_dict[key] = convert_values_to_list(test_dict[key])
for value in values:
if value not in test_dict[key]:
test_dict[key].append(value)