英文:
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}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论