【问题标题】:Print all keys from a dictionary in the format of key1.key2.key3以 key1.key2.key3 的格式打印字典中的所有键
【发布时间】: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


【解决方案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']

【讨论】:

    【解决方案2】:

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

    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 值,以防万一不是字典。因此,如果有多个子字典,您就开始将键连接在一起。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      • 2017-05-04
      • 2011-06-02
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      相关资源
      最近更新 更多