Python中关于多维数组的问题请教

我以前是写 PHP 的,PHP 里面有一个索引数组的功能感觉很好用,比如说在 PHP 里面,可以这么写
$array[‘accountId’][‘name’] = ‘v2ex’

即使我没有初始化过 accountId 或者 name 这两个 key,PHP 会帮我自动创建

这两天写 Python,发现 Python 中如果使用 dict 来实现相同的功能,需要先判断一下 key 是否存在,然后先进行初始化才能赋值操作,感觉比较繁琐。

在网上查了一些,defaultdict 之类的,感觉也没解决问题。请问是我的代码写的有问题,还是说 Python 的就是如此?有没有什么好的解决方法?
Python中关于多维数组的问题请教


5 回复

这在 PHP 里叫多维数组?在其他语言里叫 Dictionary, Map, Associative Array。
看 defaultdict
https://docs.python.org/3/library/collections.html#collections.defaultdict


我无法理解你的问题。

from collections import defaultdict
import json

def tree():
“”"
Factory that creates a defaultdict that also uses this factory
“”"
return defaultdict(tree)

root = tree()
root[‘Page’][‘Python’][‘defaultdict’][‘Title’] = 'Using defaultdict’
root[‘Page’][‘Python’][‘defaultdict’][‘Subtitle’] = 'Create a tree’
root[‘Page’][‘Java’] = None

print(json.dumps(root, indent=4))

运行结果如下:

{
“Page”: {
“Python”: {
“defaultdict”: {
“Subtitle”: “Create a tree”,
“Title”: “Using defaultdict”
}
},
“Java”: null
}
}

https://segmentfault.com/a/1190000010280700

这还繁琐吗…你没用过 C/C++吧,不对,这貌似就是 PHP 的 feature 吧…不觉得很危险吗



感谢两位,我再仔细看看 defaultdict

恩,不过也很方便吧,看用来做什么

回到顶部