2010-08-09 45 views
5

我有一个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 

唯一我能想到的方法就像使用正则表达式并遍历整个字典,但我是n不知道如果这是最好的方法(我也不是精通正则表达式)。

感谢您的任何帮助。不使用正则表达式

回答

5

一种可能性是只使用startswith

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

可以str.find使用:

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

好吧,你一定要遍历整个字典。

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)) 

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

1

您的字典结构是否已修复?这将是更好的做到这一点使用嵌套的字典:

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

这里的基本数据结构是一棵树,但是Python不具有内置

+0

你可能想看到我的帖子http://stackoverflow.com/questions/3350413/is-there-a-faster-way-to-get-subtrees-from-tree-like-structures-in-python-than- th/3350642#3350642如果你认为树的结构。 – 2010-08-09 17:55:16

1

这消除缩进的一个水平,这可能。使for循环更加易读体内的代码在某些情况下

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

如果您发现性能是一个问题,可以考虑使用的trie而不是字典