I want to append a dictionary to a list. Thereafter, I would like to append the same dictionary to the list with one value changed in the dictionary. In the given example, I want to end up with a list of 2 dictionaries where one value is different from the other. However, when i try to accomplish this the value is changed in both dictionaries in the list. I am using the following example code:
details = []
string1 = 'I want some information from this string in a dictionary'
string2 = 'A short string'
row = {'first_word': string1.split(' ')[0],
'last_word': string1.split(' ')[-1],
'length_string': len(string1)}
details.append(row)
if len(string2) < 50:
row['length_string'] = 'String2 is too short.'
details.append(row)
for x in details:
print(x)
This yields:
{'first_word': 'I', 'last_word': 'dictionary', 'length_string': 'String2 is too short.'}
{'first_word': 'I', 'last_word': 'dictionary', 'length_string': 'String2 is too short.'}
Changing the dict value updates the whole list it seems. I think I'm missing something obvious. Can someone please assist me with getting the below output?
{'first_word': 'I', 'last_word': 'dictionary', 'length_string': 56}
{'first_word': 'I', 'last_word': 'dictionary', 'length_string': 'String2 is too short.'}