2010-08-09 47 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而不是字典