Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Updating a value in a deeply nested dictionary

I am importing and manipulating some deeply nested JSON (imported as a dictionary). It can assign the values just fine using code like:

query['query']['function_score']['query']['multi_match']['operator'] = 'or'
query['query']['function_score']['query']['multi_match'].update({
        'minimum_should_match' : '80%' })  

But it's ugly and cumbersome as nuts. I'm wondering if there's a cleaner way to assign values to deep-nested keys that's reasonably efficient?

I've read about possibly using an in-memory SQLlite db, but the data is going back into json after a bit of manipulation.

like image 201
tarponjargon Avatar asked Apr 18 '26 18:04

tarponjargon


2 Answers

multi_match = query['query']['function_score']['query']['multi_match']
multi_match['operator'] = 'or'
multi_match.update({'minimum_should_match' : '80%' })
like image 89
宏杰李 Avatar answered Apr 21 '26 07:04

宏杰李


JSONPath (via 'jsonpath_rw') makes it less cumbersome:

Previous:

>>> query
{u'query': {u'function_score': {u'query': {u'multi_match': {u'min_should_match': u'20%'}}}}}

Update:

>>> found = jsonpath_rw.parse("$..multi_match").find(query)[0]
>>> found.value["operator"] == "or"
>>> found.value["min_should_match"] = "80%"`

Afterwards:

>>> query
{u'query': {u'function_score': {u'query': {u'multi_match': {'min_should_match': '80%', u'operator': u'or'}}}}}
like image 28
ma-ti Avatar answered Apr 21 '26 07:04

ma-ti