I have a dictionary of lists.
I have a function to combine 2x of these into a single new object, like this:
def combine(d_a, d_b):
new_dict = {}
dict_a_copy = d_a.copy()
dict_b_copy = d_b.copy()
for entry_key in dict_a_copy.keys():
if entry_key in dict_b_copy:
# Entry exists - append values
for list_item in dict_a_copy[entry_key]:
dict_b_copy[entry_key].append(list_item)
else:
# New entry
dict_b_copy[entry_key] = dict_a_copy[entry_key]
new_dict = dict_b_copy
return new_dict
if __name__ == "__main__":
dict_a = {"Item1": [1,2,3], "Item2":[4,5,6]}
dict_b = {"Item1": [7,8,9]}
print("dict_a = " + str(dict_a))
print("dict_b = " + str(dict_b))
print("\nCombining")
dict_ab = combine(dict_a, dict_b)
print("dict_a = " + str(dict_a))
print("dict_b = " + str(dict_b))
print("dict_ab = " + str(dict_ab))
When I run it, I expect to see this:
dict_a = {'Item1': [1, 2, 3], 'Item2': [4, 5, 6]}
dict_b = {'Item1': [7, 8, 9]}
Combining
dict_a = {'Item1': [1, 2, 3], 'Item2': [4, 5, 6]}
dict_b = {'Item1': [7, 8, 9]}
dict_ab = {'Item1': [7, 8, 9, 1, 2, 3], 'Item2': [4, 5, 6]}
However, dict_b
gets modified as well and the result is this:
dict_a = {'Item1': [1, 2, 3], 'Item2': [4, 5, 6]}
dict_b = {'Item1': [7, 8, 9]}
Combining
dict_a = {'Item1': [1, 2, 3], 'Item2': [4, 5, 6]}
dict_b = {'Item1': [7, 8, 9, 1, 2, 3]}
dict_ab = {'Item1': [7, 8, 9, 1, 2, 3], 'Item2': [4, 5, 6]}
If I change dict_b.items
to use a unique dictionary name, then it works:
dict_b.items = {"Item3": [7,8,9]}
This gives:
dict_a = {'Item1': [1, 2, 3], 'Item2': [4, 5, 6]}
dict_b = {'Item3': [7, 8, 9]}
Combining
dict_a = {'Item1': [1, 2, 3], 'Item2': [4, 5, 6]}
dict_b = {'Item3': [7, 8, 9]}
dict_ab = {'Item3': [7, 8, 9], 'Item1': [1, 2, 3], 'Item2': [4, 5, 6]}
Can someone explain what is happening?