Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Managing square brackets in dictionary keys with dpath library

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}}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

It seems like dpath uses fnmatch.fnmatch standard library under the hood. As per the 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}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading