在 Python 中创建 2D 字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25924244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:49:12  来源:igfitidea点击:

Creating 2D dictionary in Python

pythondictionarysetkey2d

提问by user2921139

I have a list of details from an output for "set1" which are like "name", "place", "animal", "thing" and a "set2" with the same details.

我有一个“set1”输出的详细信息列表,比如“name”、“place”、“animal”、“thing”和具有相同细节的“set2”。

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

我想用dict_names[setx]['name']...etc 在这些行上创建一个字典。

Is that the best way to do it? If not how do I do it?

这是最好的方法吗?如果不是我该怎么做?

I am not sure how 2D works in dictionary.. Any pointers?

我不确定 2D 在字典中是如何工作的..有什么指点吗?

采纳答案by Cory Kramer

It would have the following syntax

它将具有以下语法

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

You can then look things up like

然后你可以查找类似的东西

>>> dict_names['d1']['name']
'bob'

回答by elyase

Something like this would 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 about it as a nested structure (instead of a 2D matrix):

等。最好将其视为嵌套结构(而不​​是 2D 矩阵):

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

Take a look herefor an easy way to visualize nested dictionaries.

看看这里的一个简单的方法来可视化嵌套字典。

回答by Shamiul Hasan Rumman

Something like this should work.

像这样的事情应该有效。

dictionary = dict()
dictionary[1] = dict()
dictionary[1][1] = 3
print(dictionary[1][1])

You can extend it to higher dimensions as well.

您也可以将其扩展到更高的维度。