使用dpath库管理字典键中的方括号

huangapple go评论69阅读模式
英文:

Managing square brackets in dictionary keys with dpath library

问题

使用dpath库时,我在处理包含方括号键的字典时遇到了问题。从文档中我看到方括号被视为正则表达式的元素。然而,在我的情况下,这导致了问题,因为我只想它们是"普通"的方括号。

我尝试用反斜杠\[转义方括号,但结果仍然相同。

代码示例

import dpath

d = {'Position': {'Position x [mm]': 3}}
dpath.search(d, 'Position/Position x [mm]/*')

这会输出:{}而不是预期的{'Position': {'Position x [mm]': 3}}

英文:

Using the dpath library, I'm having trouble working with a dictionary with keys containing square brackets. From the docs I see that square brackets are considered as elements of regular exporessions. However, this is causing the issue in my case, because I just want them to be "normal" square brackets.

I tried to escape the square brackets with a backspace \[, but the result is the same.

Code example

import dpath

d = {'Position': {'Position x [mm]': 3}}
dpath.search(d, 'Position/Position x [mm]/*')

This outputs: {} instead of the expected {'Position': {'Position x [mm]': 3}}

Maybe there is already a solution for the problem, but I did not find it in the docs.

答案1

得分: 3

看起来dpath在底层使用了*fnmatch*库fnmatch模块提供对Unix shell风格的通配符的支持,这与正则表达式不同)。根据fnmatch文档的描述,

对于字面匹配,请将元字符括在方括号中。例如,'[?]'匹配字符'?'。

因此,您需要将[替换为[[],将]替换为[]]以获得期望的匹配结果。

>>> import dpath
>>> 
>>> d = {'Position': {'Position x [mm]': 3}}
>>> dpath.search(d, 'Position/Position x [[]mm[]]')
{'Position': {'Position x [mm]': 3}}
英文:

It seems like dpath uses fnmatch library under the hood(fnmatch module provides support for Unix shell-style wildcards, which are not the same as regular expressions). As per the fnmatch documentation,

> For a literal match, wrap the meta-characters in brackets. For
> example, '[?]' matches the character '?'

So you have to replace the [ with [[] and ] with []] to get the expected match result.

>>> import dpath
>>> 
>>> d = {'Position': {'Position x [mm]': 3}}
>>> dpath.search(d, 'Position/Position x [[]mm[]]')
{'Position': {'Position x [mm]': 3}}

huangapple
  • 本文由 发表于 2023年6月19日 16:12:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76504780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定