在python中声明多维字典

编程入门 行业动态 更新时间:2024-10-24 16:33:14
本文介绍了在python中声明多维字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要在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] = 5

dict.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中声明多维字典

本文发布于:2023-07-31 15:40:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1260012.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多维   字典   声明   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!