【发布时间】:2018-12-24 16:05:49
【问题描述】:
我想获取列表中嵌套字典的所有键的路径。例如,如果我的 dict 如下所示
{
"persons": [{
"id": "f4d322fa8f552",
"address": {
"building": "710",
"coord": "[123, 465]",
"street": "Avenue Road",
"zipcode": "12345"
},
"cuisine": "Chinese",
"grades": [{
"date": "2013-03-03T00:00:00.000Z",
"grade": "B",
"score": {
"x": 3,
"y": 2
}
}, {
"date": "2012-11-23T00:00:00.000Z",
"grade": "C",
"score": {
"x": 1,
"y": 22
}
}],
"name": "Shash"
}]
}
我想得到这样的路径
path = [['persons'], ['persons','id'],['persons','address'],['persons','address','building']...] 直到最后一个键。
我试图遍历整个字典来附加路径变量。试图从Print complete key path for all the values of a python nested dictionary 获得一些灵感,但我无法获得列表中的路径。
有没有其他可能的方法来解决这个问题。
【问题讨论】:
-
获取
path是什么意思,是递归遍历数据结构吗?你能展示你尝试过的东西吗? -
但
id实际上在persons的列表中,而不是persons的键作为字典。您不想考虑id在列表中的事实吗?否则,您预期输出中的路径将毫无用处。 -
d['persons']['id']会产生错误,不确定是路径吗?
标签: python dictionary key