Creating a 2D Dictionary in Python

I have a list of parts from the output for "set1" that look like "name", "place", "animal", "thing", and "set2" with the same details.

I want to create a dictionary with dict_names[setx]['name']... etc. In these lines.

Is this the best way to do this? If not, how to do it?

I'm not sure how 2D works in a dictionary .. Any pointers?

+6
source share
2 answers

It will have the following syntax

 dict_names = {'d1' : {'name':'bob', 'place':'lawn', 'animal':'man'}, 'd2' : {'name':'spot', 'place':'bed', 'animal':'dog'}} 

Then you can look something like

 >>> dict_names['d1']['name'] 'bob' 
+10
source

Something like this will work:

 set1 = { 'name': 'Michael', 'place': 'London', ... } # same for set2 d = dict() d['set1'] = set1 d['set2'] = set2 

Then you can do:

 d['set1']['name'] 

etc .. It is better to think of it as a nested structure (instead of a two-dimensional matrix):

 { 'set1': { 'name': 'Michael', 'place': 'London', ... } 'set2': { 'name': 'Michael', 'place': 'London', ... } } 

Look here for an easy way to visualize nested dictionaries.

+2
source

Source: https://habr.com/ru/post/975509/


All Articles