"How to update values within lists within a dictionary?" is a good question. Suppose I have a dictionary of lists and I want to change a value within one of those lists.
import copy
i = 1
input_sentence_dict = {i: []}
input_sentence_dict[1] = "['I', 'have', 'a', 'gift', 'for', 'Carmine', '.']"
input_sentence_dict[2] = "['I', 'gave', 'it', 'to', 'her', '.']"
import pprint
pp = pprint.PrettyPrinter(indent=4)
print('input_sentence_dict:')
pp.pprint(input_sentence_dict)
'''
input_sentence_dict:
{ 1: ['I', 'have', 'a', 'gift', 'for', 'Carmine', '.'],
2: ['I', 'gave', 'it', 'to', 'her', '.']}
'''
output_sentence_dict = copy.deepcopy(input_sentence_dict)
print('output_sentence_dict:')
pp.pprint(output_sentence_dict)
'''
output_sentence_dict:
{ 1: ['I', 'have', 'a', 'gift', 'for', 'Carmine', '.'],
2: ['I', 'gave', 'it', 'to', 'her', '.']}
'''
# example of indexing:
print(output_sentence_dict[2][1:3])
# ['gave', 'it']
Through indexing, you can easily change a value within one of those lists. For example:
output_sentence_dict[2][2] = 'a book'
pp.pprint(output_sentence_dict)
'''
{ 1: ['I', 'have', 'a', 'gift', 'for', 'Carmine', '.'],
2: ['I', 'gave', 'a book', 'to', 'her', '.']}
'''
Note. If you simply copy a dictionary (e.g. dict2 = dict1
), edits to one affects the other. You need to "deepcopy" the source dictionary to ensure that you work on a truly different object, leaving the source object unperturbed.
import copy
dict2 = copy.deepcopy(dict1)
You may then edit dict2
, leaving dict1
unaltered.
This is well-described in this StackOverflow thread: How to copy a dictionary and only edit the copy
Working with "shallow copies," e.g.
dict2 = dict1
# or
dict2 = dict(dict1)
will result in silent errors. In the example above, if you do not use copy.deepcopy(dict)
, changes made to output_sentence_dict
will also silently propagate to input_sentence_dict
.