以key1.key2.key3的格式打印字典中的所有键

时间:2018-01-31 22:17:30

标签: python json dictionary key

这是我的字典(或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

如您所见,最后几行是错误的。

有人有建议吗?不仅限于此脚本,欢迎使用其他方法,但不使用任何模块。

2 个答案:

答案 0 :(得分:1)

您可以使用递归:

d = {'$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'}}}}}
def display_keys(s, last=None):
   for a, b in s.items():
      if not isinstance(b, dict):
          yield "{}.{}".format(last, a) if last else str(a)
      else:
         for h in display_keys(b, str(a) if not last else '{}.{}'.format(last, a)):
           yield h

 print(list(display_keys(d)))

输出:

['$schema', 'name', 'type', 'properties.id.type', 'properties.id.description', 'properties.id.required', 'properties.name.type', 'properties.name.description', 'properties.name.required', 'properties.price.type', 'properties.price.minimum', 'properties.price.required', 'properties.tags.type', 'properties.tags.items.type', 'properties.stock.type', 'properties.stock.properties.warehouse.type', 'properties.stock.properties.retail.type']

答案 1 :(得分:0)

我认为您通过更新keys使其变得复杂。 Python中的字符串是 immutable 。我们每次都可以将扩展密钥传递给下一个递归级别,所以使用:

def myprint(d, keys = ''):
    for k, v in d.items():
        if isinstance(v, dict):
            myprint(v, '{}{}.'.format(keys, k))
        else:
            print('{}{}'.format(keys, k))

然后产生:

>>> myprint(d)
$schema
name
type
properties.id.type
properties.id.description
properties.id.required
properties.name.type
properties.name.description
properties.name.required
properties.price.type
properties.price.minimum
properties.price.required
properties.tags.type
properties.tags.items.type
properties.stock.type
properties.stock.properties.warehouse.type
properties.stock.properties.retail.type

您的代码存在的问题是,只有在字典的情况下,您才会恢复旧的keys值。因此,如果存在多个子项,则开始将键连接在一起。