I am parsing JSON that stores various code snippets and I am first building a dictionary of languages used by these snippets:
snippets = {'python': {}, 'text': {}, 'php': {}, 'js': {}}
Then when looping through the JSON I’m wanting add the information about the snippet into its own dictionary to the dictionary listed above. For example, if I had a JS snippet – the end result would be:
snippets = {'js':
{"title":"Script 1","code":"code here", "id":"123456"}
{"title":"Script 2","code":"code here", "id":"123457"}
}
Not to muddy the waters – but in PHP working on a multi-dimensional array I would just do the following (I am lookng for something similiar):
snippets['js'][] = array here
I know I saw one or two people talking about how to create a multidimensional dictionary – but can’t seem to track down adding a dictionary to a dictionary within python. Thanks for the help.
This is called autovivification:
You can do it with
defaultdictIf the idea is to have lists, you can do:
The idea for defaultdict it to create automatically the element when the key is accessed. BTW, for this simple case, you can simply do: