Skip to main content
 首页 » 编程设计

python之我如何评估 python 集合上的路径表达式,就像我可能对 XML 文档使用 XPath 一样

2024年10月24日33cloudgamer

XML 具有 XPath。 Perl 有数据::路径。 python 中是否存在任何东西来评估 python 对象或至少集合的路径表达式?

考虑这个集合:

deployments = [ 
    {'type': 'database', 
     'owner': 'fred', 
     'server': 'db-F'}, 
    {'type': 'database', 
     'owner': 'carol', 
     'server': 'db-W'}, 
    {'type': 'application', 
     'owner': 'carol', 
     'server': 'web-A'}, 
    {'type': 'application', 
     'owner': 'anthony', 
     'server': 'web-A'}   ] 

如果我能写一个像这样调用的“path_search”函数会很有帮助:

path_search(deployments, ".//*[owner = 'carol']") 

返回这个:

[   {'type': 'database', 
     'owner': 'carol', 
     'server': 'db-W'}, 
    {'type': 'application', 
     'owner': 'carol', 
     'server': 'web-A'}   ] 

路径优于硬编码结构遍历的原因是我的配置在结构和嵌套方面因文件而异。

请您参考如下方法:

  1. 有一个dpath PyPI 中的库。

A python library for accessing and searching dictionaries via /slashed/paths ala xpath

但该库似乎只专注于在嵌套词典中进行搜索。

  1. 还有一个jsonpath-rw支持不同的搜索表达式来查找项目的库。