在字典中打印特定子集的键

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

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

感谢任何帮助。

5个回答

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没有内置该数据结构。


如果你想到了树形结构,你可以看看我发布在stackoverflow上的帖子http://stackoverflow.com/questions/3350413/is-there-a-faster-way-to-get-subtrees-from-tree-like-structures-in-python-than-th/3350642#3350642。 - Tony Veijalainen

1

这将消除一层缩进,在某些情况下可能会使for循环体中的代码更易读

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

如果您发现性能成为问题,请考虑使用trie而不是字典。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接