打印字典中特定子集的键

5 投票
5 回答
722 浏览
提问于 2025-04-16 02:32

我在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

我能想到的唯一方法就是用正则表达式,然后遍历整个字典,但我不确定这是否是最好的方法(而且我对正则表达式也不是很熟悉)。

谢谢大家的帮助。

5 个回答

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

你可以通过使用合适的数据结构来加快这个过程,比如树。

5

一种不使用正则表达式的方法是直接用 startswith

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

撰写回答