Reputation: 458
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.
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.
Upvotes: 1
Views: 153
Reputation: 24817
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}}
Upvotes: 3