Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 739
RealRageDontQuit Avatar asked Jan 27 '26 01:01

RealRageDontQuit


2 Answers

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.

like image 157
Andrew Merrill Avatar answered Jan 29 '26 15:01

Andrew Merrill


You're looking for the update method:

d['A'].update({'b':3})
like image 43
ForceBru Avatar answered Jan 29 '26 14:01

ForceBru