Updating and creating a multidimensional dictionary in Python

I am parsing JSON, which stores various pieces of code, and I first create a dictionary of languages ​​used by these pieces:

snippets = {'python': {}, 'text': {}, 'php': {}, 'js': {}} 

Then, when looping through JSON, I want to add fragment information to my dictionary in the dictionary above. For example, if I had a JS fragment, the end result would be:

 snippets = {'js': {"title":"Script 1","code":"code here", "id":"123456"} {"title":"Script 2","code":"code here", "id":"123457"} } 

Do not stir up the water, but in PHP working on a multidimensional array, I would just do the following (I look something similar):

 snippets['js'][] = array here 

I know that one or two people talked about how to create a multidimensional dictionary, but they cannot track the addition of the dictionary to the dictionary in python. Thanks for the help.

+6
source share
2 answers

This is called autovivification :

You can do it with defaultdict

 def tree(): return collections.defaultdict(tree) d = tree() d['js']['title'] = 'Script1' 

If the idea is to have lists, you can do:

 d = collections.defaultdict(list) d['js'].append({'foo': 'bar'}) d['js'].append({'other': 'thing'}) 

The idea of ​​defaultdict is to automatically create an element when accessing a key. BTW, for this simple case, you can simply:

 d = {} d['js'] = [{'foo': 'bar'}, {'other': 'thing'}] 
+11
source

Of

 snippets = {'js': {"title":"Script 1","code":"code here", "id":"123456"} {"title":"Script 2","code":"code here", "id":"123457"} } 

It seems to me that you want to have a list of dictionaries. Here is some python code that hopefully leads to what you want

 snippets = {'python': [], 'text': [], 'php': [], 'js': []} snippets['js'].append({"title":"Script 1","code":"code here", "id":"123456"}) snippets['js'].append({"title":"Script 1","code":"code here", "id":"123457"}) print(snippets['js']) #[{'code': 'code here', 'id': '123456', 'title': 'Script 1'}, {'code': 'code here', 'id': '123457', 'title': 'Script 1'}] 

It is clear?

+6
source

All Articles