python orderedict:访问di中的特定深度

2024-09-26 17:58:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个功能,需要一个dict和打印它的内容在一个很好的性感的方式。你知道吗

我想编辑函数来控制dict的深度,但我有点迷路了。你知道吗

函数如下:

def print_dict(_dict, indent=""):
    for k, v in _dict.items():
        if hasattr(v, 'items'):
            print "%s(%s::" % (indent, k)
            print_dict(v, indent + "  ")
            print "%s)" % indent
        elif isinstance(v, list):
            print "%s(%s::" % (indent, k)
            for i in v:
                print_dict(dict(i), indent + "  ")
            print "%s)" % indent
       else:
            print "%s(%s::%s)" % (indent, k, v)

输出:

(Axis::
  (@Name::kfcQ1[{kfcQ1_1}].kfcQ1_grid)
  (@MdmName::kfcQ1[{kfcQ1_1}].kfcQ1_grid)
  (@UseMetadataDefinition::true)
  (@Label::kfcQ1_1. Veuillez sélectionner votre réponse)
  (Labels::
    (Label::
      (@Language::FRA)
      (@Text::kfcQ1_1. Veuillez sélectionner votre réponse?)
    )
  )
  (Elements::
    (Element::
      (Style::None)
      (@Name::UnweightedBase)
      (@MdmName::)
      (@IsHiddenWhenColumn::true)
      (Labels::
        (Label::
          (@Language::FRA)
          (@Text::Base brute)
        )
      )
    )   
)

期望输出

print_dict(_dict, depth=0, indent="")
(Axis::
  (@Name::kfcQ1[{kfcQ1_1}].kfcQ1_grid)
  (@MdmName::kfcQ1[{kfcQ1_1}].kfcQ1_grid)
  (@UseMetadataDefinition::true)
  (@Label::kfcQ1_1. Veuillez sélectionner votre réponse)
)

真希望这有道理。你知道吗


Tags: 函数nametrueforlabeldictgridprint
1条回答
网友
1楼 · 发布于 2024-09-26 17:58:20

更改函数的签名,使其接受两个新参数:depthmax_depth

def print_dict(_dict, indent="", depth=0, max_depth=-1):

在每次调用print_dict之前,递增深度:

print_dict(v, indent + "  ", depth=depth + 1, max_depth=max_depth)
print_dict(dict(i), indent + "  ", depth=depth + 1, max_depth=max_depth)

最后,在函数的开头,检查depthmax_depth

def print_dict(_dict, indent="", depth=0, max_depth=-1):
    if max_depth > 0 and depth > max_depth:
        return

相关问题 更多 >

    热门问题