在python中声明一个多维字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29348345/
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-19 04:27:27  来源:igfitidea点击:

Declaring a multi dimensional dictionary in python

pythondictionary

提问by Saurabh

I need to make a two dimensional dictionary in python. e.g. new_dic[1][2] = 5

我需要在python中制作一个二维字典。例如new_dic[1][2] = 5

When I make new_dic = {}, and try to insert values, I get a KeyError:

当我 makenew_dic = {}并尝试插入值时,我得到一个KeyError

new_dic[1][2] = 5
KeyError: 1

How to do this?

这该怎么做?

回答by Martijn Pieters

A multi-dimensional dictionary is simply a dictionary where the values are themselves also dictionaries, creating a nested structure:

多维字典只是一个字典,其中值本身也是字典,创建嵌套结构:

new_dic = {}
new_dic[1] = {}
new_dic[1][2] = 5

You'd have to detect that you already created new_dic[1]each time, though, to not accidentally wipe that nested object for additional keys under new_dic[1].

但是,您必须new_dic[1]每次都检测到您已经创建了,以免意外擦除该嵌套对象以获取new_dic[1].

You can simplify creating nested dictionaries using various techniques; using dict.setdefault()for example:

您可以使用各种技术简化创建嵌套字典的过程;使用dict.setdefault()例如:

new_dic.setdefault(1, {})[2] = 5

dict.setdefault()will only set a key to a default value if the key is still missing, saving you from having to test this each time.

dict.setdefault()如果密钥仍然丢失,只会将密钥设置为默认值,从而使您不必每次都进行测试。

Simpler still is using the collections.defaultdict()typeto create nested dictionaries automatically:

更简单的仍然是使用collections.defaultdict()类型自动创建嵌套字典:

from collections import defaultdict

new_dic = defaultdict(dict)
new_dic[1][2] = 5

defaultdictis just a subclass of the standard dicttype here; every time you try and access a key that doesn't yet exist in the mapping, a factory function is called to create a new value. Here that's the dict()callable, which produces an empty dictionary when called.

defaultdict这里只是标准dict类型的一个子类;每次尝试访问映射中尚不存在的键时,都会调用工厂函数来创建新值。这是dict()callable,它在调用时生成一个空字典。

Demo:

演示:

>>> new_dic_plain = {}
>>> new_dic_plain[1] = {}
>>> new_dic_plain[1][2] = 5
>>> new_dic_plain
{1: {2: 5}}
>>> new_dic_setdefault = {}
>>> new_dic_setdefault.setdefault(1, {})[2] = 5
>>> new_dic_setdefault
{1: {2: 5}}
>>> from collections import defaultdict
>>> new_dic_defaultdict = defaultdict(dict)
>>> new_dic_defaultdict[1][2] = 5
>>> new_dic_defaultdict
defaultdict(<type 'dict'>, {1: {2: 5}})

回答by NDevox

Do you mean dictor list?

你是说dict还是list

And if you mean dictdo you want the second level to be another dict? or a list?

如果你的意思dict是你想让第二级成为另一个dict?或list?

For a dictto work you need to have declared the keys ahead of time.

要使 adict工作,您需要提前声明密钥。

So if it's dictsin dictsyou need something like this:

所以如果它dictsdicts你需要这样的东西:

new_dic = {}
try:
    new_dic[1][2] = 5
except KeyError:
    new_dic[1] = {2:5}

回答by mhawke

Here is a dictionary that contains another dictionary as the value for key 1:

这是一个字典,其中包含另一个字典作为键 1 的值:

>>> new_dic = {}
>>> new_dic[1] = {2:5}
>>> new_dic
{1: {2: 5}}

The problem that you had with

你遇到的问题

new_dic={}
new_dic[1][2]=5

is that new_dic[1]does not exist, so you can't add a dictionary (or anything for that matter) to it.

new_dic[1]不存在的,所以你不能向它添加字典(或任何与此相关的东西)。

回答by itzMEonTV

Simply, you can use defaultdict

简单地说,你可以使用 defaultdict

from collections import defaultdict
new_dic = defaultdict(dict)
new_dic[1][2]=5
>>>new_dic
defaultdict(<type 'dict'>, {1: {2: 5}})

回答by Dsw Wds

u can try this, it is even easier if it is string

你可以试试这个,如果是字符串就更容易了

new_dic = {}
a = 1
new_dic[a] = {}
b = 2
new_dic[a][b] = {}
c = 5
new_dic[a][b]={c}

type

类型

new_dic[a][b]
>>>'5'

For string

对于字符串

new_dic = {}
a = "cat"
new_dic[a] = {}
b = "dog"
new_dic[a][b] = {}
c = 5
new_dic[a][b] = {c}

type

类型

new_dic["cat"]["dog"]
>>>'5'

回答by Fancy John

Check it out:

一探究竟:

def nested_dict(n, type):
    if n == 1:
        return defaultdict(type)
    else:
        return defaultdict(lambda: nested_dict(n-1, type))

And then:

进而:

new_dict = nested_dict(2, float)

Now you can:

现在你可以:

new_dict['key1']['key2'] += 5

You can create as many dimensions as you want, having the target type of your choice:

您可以根据需要创建任意数量的维度,并具有您选择的目标类型:

new_dict = nested_dict(3, list)
new_dict['a']['b']['c'].append(5)

Result will be:

结果将是:

new_dict['a']['b']['c'] = [5]

回答by Lars P

One simple way is to just use tuples as keys to a regular dictionary. So your example becomes this:

一种简单的方法是仅使用元组作为常规字典的键。所以你的例子变成了这样:

new_dic[(1, 2)] = 5

new_dic[(1, 2)] = 5

The downside is that all usages have to be with this slightly awkward convention, but if that's OK, this is all you need.

缺点是所有的用法都必须遵循这个有点尴尬的约定,但如果没问题,这就是你所需要的。

回答by Miradil Zeynalli

For project, I needed to have 2D dict of class instances, where indeces are float numbers (coordinates). What I did, was to create 2D dict using default dict, and pass my class name as a type. For ex.:

对于项目,我需要类实例的 2D 字典,其中 indeces 是浮点数(坐标)。我所做的是使用默认字典创建 2D 字典,并将我的类名作为类型传递。例如:

class myCoordinates:
    def __init__(self, args)
    self.x = args[0]
    self.y = args[1]

and then when I tried to create dictionary:

然后当我尝试创建字典时:

table = mult_dim_dict(2, myCoordinates, (30, 30))

where function 'mult_dim_dict' defined as:

其中函数 'mult_dim_dict' 定义为:

def mult_dim_dict(dim, dict_type, params):
    if dim == 1:
        if params is not None:
            return defaultdict(lambda: dict_type(params))
        else: 
            return defaultdict(dict_type)
    else:
        return defaultdict(lambda: mult_dim_dict(dim - 1, dict_type, params))

Note: you cannot pass multiple arguments, instead you can pass a tuple, containing all of your arguments. If your class, upon creation, does not need any variables to be passed, 3rd argument of function will be None:

注意:您不能传递多个参数,而是可以传递一个包含所有参数的元组。如果您的类在创建时不需要传递任何变量,则函数的第三个参数将是None

class myCoors:
def __init__(self, tuple=(0, 0)):
    self.x, self.y = tuple

def printCoors(self):
    print("x = %d, y = %d" %(self.x, self.y))


def mult_dim_dict(dim, dict_type, params):
    if dim == 1:
        if params is not None:
            return defaultdict(lambda: dict_type(params))
        else:
            return defaultdict(dict_type)
    else:
        return defaultdict(lambda: mult_dim_dict(dim - 1, dict_type, params))

dict = mult_dim_dict(2, myCoors, None)
dict['3']['2'].x = 3
dict['3']['2'].y = 2

dict['3']['2'].printCoors()  # x = 3, y = 2 will be printed

dict = mult_dim_dict(2, myCoors, (30, 20))
dict['3']['2'].printCoors()  # x = 30, y = 20 will be printed