Search code examples
pythondictionaryappendappendchild

How to append to a nested dictionary in python


I have the following nested dictionary:

d = {'A':{'a':1}, 'B':{'b':2}}

I want to add values to d without overwriting.

So if I want to append the value ['A', 'b', 3] the dictionary should read:

d = {'A':{'a':1, 'b':3}, 'B':{'b':2}}

d['A'].append({'b':3}) errors with:

AttributeError: 'dict' object has no attribute 'append'

I don't know what the nested dictionary will be in advance. So saying:

d['A'] = {'a':1, 'b':3}

will not work for my case as I am "discovering/calculating" the values as the script runs.

Thanks


Solution

  • In python, append is only for lists, not dictionaries.

    This should do what you want:

    d['A']['b'] = 3

    Explanation: When you write d['A'] you are getting another dictionary (the one whose key is A), and you can then use another set of brackets to add or access entries in the second dictionary.