0

The dictionary structure is:

storage = {}   
storage['first'] = {}   
storage['middle'] = {}  
storage['last'] = {}

The first insertion made to this dictionary is:

me = 'Magnus Lie Hetland'   
storage['first']['Magnus'] = [me]  
storage['middle']['Lie'] = [me] 
storage['last']['Hetland'] = [me]

Then the following statements are executed:

my_sister = 'Anne Lie Hetland'
storage['first'].setdefault('Anne', []).append(my_sister)

As per the documentation setdefault should insert the key 'Anne' with a value [] (New Empty list) and then it should append my_sister. So why it is appending my_sister to the pre-existing list and not creating new list.

Brijesh Joshi
  • 19
  • 1
  • 10
  • 1
    what do you think the output should be? – hchw May 07 '20 at 14:28
  • 1
    Is `{'first': {'Magnus': ['Magnus Lie Hetland'], 'Anne': ['Anne Lie Hetland']}, 'middle': {'Lie': ['Magnus Lie Hetland']}, 'last': {'Hetland': ['Magnus Lie Hetland']}}` something else than you expected? – Błotosmętek May 07 '20 at 14:29
  • @hchw `storage['middle']['Lie']' should give output '['Magnus Lie Hetland'] , [ 'Anne Lie Hetland']` and not a single list containing both names. – Brijesh Joshi May 07 '20 at 14:32
  • It doesn't result in a single list containing both names. See e.g. the comment from @Błotosmętek. – larsks May 07 '20 at 14:33
  • When I run your code I get what you expect! – hchw May 07 '20 at 14:33
  • Your code above appends your sister only to `storage['first']['Anne']`, why do you expect her to be added to `storage['middle']['Lie']`? There is nothing in your code to cause it. – Błotosmętek May 07 '20 at 14:40

0 Answers0