【问题标题】:Printing a particular subset of keys in a dictionary在字典中打印特定的键子集
【发布时间】:2010-08-09 14:54:47
【问题描述】:

我有一个 Python 字典,其中的键是路径名。例如:

dict["/A"] = 0
dict["/A/B"] = 1
dict["/A/C"] = 1

dict["/X"] = 10
dict["/X/Y"] = 11

我想知道,在给定任何键的情况下,打印所有“子路径”的好方法是什么。

例如,给定一个名为“print_dict_path”的函数来执行此操作,类似于

print_dict_path("/A")

print_dict_path("/A/B")

会打印出类似的内容:

"B" = 1
"C" = 1

我能想到的唯一方法是使用正则表达式并浏览整个字典,但我不确定这是否是最好的方法(我也不那么精通正则表达式)。

感谢您的帮助。

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    不使用正则表达式的一种可能性是只使用startswith

    top_path = '/A/B'
    for p in d.iterkeys():
        if p.startswith(top_path):
            print d[p]
    

    【讨论】:

      【解决方案2】:

      你可以使用 str.find:

      def print_dict_path(prefix, d):
          for k in d:
              if k.find(prefix) == 0:
                  print "\"{0}\" = {1}".format(k,d[k])
      

      【讨论】:

        【解决方案3】:

        嗯,你肯定要遍历整个字典。

        def filter_dict_path( d, sub ):
            for key, val in d.iteritems():
                if key.startswith(sub): ## or do you want `sub in key` ?
                    yield key, val
        
        print dict(filter_dict_path( old_dict, sub ))
        

        您可以通过使用适当的数据结构来加快速度:树。

        【讨论】:

          【解决方案4】:

          你的字典结构是固定的吗?使用嵌套字典会更好:

          {
              "A": {
                  "value": 0
                  "dirs": {
                      "B": {
                          "value": 1
                      }
                      "C": {
                          "value": 1
                      }
                  }
              "X": {
                  "value": 10
                  "dirs": {
                      "Y": {
                          "value": 11
                      }
          }
          

          这里的底层数据结构是一棵树,但 Python 没有内置。

          【讨论】:

          【解决方案5】:

          这去除了一级缩进,这可能会使 for 循环主体中的代码在某些情况下更具可读性

          top_path = '/A/B'
          for p in (p for p in d.iterkeys() if p.startswith(top_path)):
              print d[p]
          

          如果您发现性能有问题,请考虑使用 trie 代替字典

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-11-12
            • 2019-11-04
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多