I am new to Python (and programming).
I would like to change the dictionary in a for loop, alternating the dictionary key. However, I wrote the following code, which was unsuccessful:
dict1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
dict2 = dict.fromkeys(dict1.values(),[])
for key in dict2:
if key == 'value1':
dict2[key].extend(['test1', 'test2'])
elif key == 'value2':
dict2[key].extend(['test3', 'test4'])
elif key == 'value3':
dict2[key].extend(['test5', 'test6'])
print (dict2['value1'])
print (dict2['value3'])
I expected the results to be as follows:
['test5', 'test6']
['test1', 'test2']
but I really got:
['test5', 'test6', 'test3', 'test4', 'test1', 'test2']
['test5', 'test6', 'test3', 'test4', 'test1', 'test2']
I think the problem is that I made a dictionary from another dictionary using "dict.fromkeys", but I could not understand why this is problematic, even if it is.
Thank you for the attention. Wait for your offers.