我需要在python中制作一个二维字典.例如new_dic[1][2] = 5
I need to make a two dimensional dictionary in python. e.g. new_dic[1][2] = 5
当我创建new_dic = {}并尝试插入值时,我得到一个KeyError:
When I make new_dic = {}, and try to insert values, I get a KeyError:
new_dic[1][2] = 5 KeyError: 1该怎么做?
推荐答案多维字典只是一个字典,其中值本身也是字典,创建了嵌套结构:
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不过,您每次都必须检测到您已经创建了new_dic[1],以免意外擦拭嵌套的对象以获取new_dic[1]下的其他键.
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].
您可以使用多种技术简化创建嵌套词典的过程;例如,使用 dict.setdefault()
You can simplify creating nested dictionaries using various techniques; using dict.setdefault() for example:
new_dic.setdefault(1, {})[2] = 5dict.setdefault()仅在密钥仍然丢失的情况下才将密钥设置为默认值,从而使您不必每次都进行测试.
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.
Simpler仍在使用 collections.defaultdict()类型自动创建嵌套字典:
Simpler still is using the collections.defaultdict() type to create nested dictionaries automatically:
from collections import defaultdict new_dic = defaultdict(dict) new_dic[1][2] = 5这里的
defaultdict只是标准dict类型的子类;每次尝试访问映射中尚不存在的键时,都会调用工厂函数来创建新值.这就是 dict()可调用,它在被调用时会生成一个空字典.
defaultdict is just a subclass of the standard dict type 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.
演示:
>>> 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}})更多推荐
在python中声明多维字典
发布评论