The trick to this question is understanding your object types.
Let's try finding the type of dict1['c']
, as this is the one we're trying to add to:
print(type(dict1['c']))
<class 'list'>
While we're at it let's see what's inside this list:
print(type(dict1['c'][0]))
<class 'dict'>
So we have a list, and the first element of the list is a dictionary.
It looks like we want to add another dictionary to this list. But, wait, is the fact we're adding a dictionary at all relevant? Probably not, we know list
can contain any number of objects.
So let's see how we can add to a list. A quick google gives us Difference between append vs. extend list methods in Python. So we need list.append
. Let's try that:
dict1['c'].append(newvalue)
print(dict1)
{'a': 1,
'b': 2,
'c': [{'aa': 11, 'bb': 22},
{'aa': 111, 'bb': 222}]}
Hey, presto! That's exactly what we were looking for.