【发布时间】:2018-07-11 03:58:15
【问题描述】:
这是我的字典(或 JSON)
{
"$schema": "http://json-schema.org/draft-03/schema#",
"name": "Product",
"type": "object",
"properties": {
"id": {
"type": "number",
"description": "Product identifier",
"required": True
},
"name": {
"type": "string",
"description": "Name of the product",
"required": True
},
"price": {
"type": "number",
"minimum": 0,
"required": True
},
"tags": {
"type": "array",
"items": {
"type": "string"
}
},
"stock": {
"type": "object",
"properties": {
"warehouse": {
"type": "number"
},
"retail": {
"type": "number"
}
}
}
}
}
我想用这种格式key1.key2.key3 打印所有键。这是我的代码:
def myprint(d, keys = ''):
for k, v in d.items():
temp = keys
keys += k
if isinstance(v,dict):
keys += '.'
myprint(v,keys)
else:
print(keys)
keys = temp
不幸的是,这失败了,返回结果如下:
$schema
type
name
properties.stock.type
properties.stock.properties.warehouse.type
properties.stock.properties.warehouse.retail.type
properties.stock.price.minimum
properties.stock.price.type
properties.stock.price.required
properties.stock.price.tags.items.type
properties.stock.price.tags.items.type
properties.stock.price.tags.id.required
properties.stock.price.tags.id.type
properties.stock.price.tags.id.description
properties.stock.price.tags.id.name.required
properties.stock.price.tags.id.name.type
properties.stock.price.tags.id.name.description
如您所见,最后几行是错误的。
有人有建议吗?不仅限制此脚本,还欢迎使用其他方法,但不使用任何模块。
【问题讨论】:
-
“没有使用模块”是什么意思?
-
@wim 像没有导入集合(或其他模块)
-
collections内置于任何 Python 安装中。那么,为什么不能使用呢? -
@wim: 因为这可能是功课
-
@WillemVanOnsem 作业?如果不使用导入模块,我从来没有收到过这个级别的硬件。奇怪吗?
标签: python json dictionary key