2

I had a strange issue while merging 2 dictionaries in Python.

Let's say having a valid empty body for performing ElasticSearch queries:

>>> a = {'aggs': {}, 'query': {'bool': {'must': [], 'should': []}}}

When I print it:

>>> a
{'aggs': {}, 'query': {'bool': {'must': [], 'should': []}}}

Is running perfectly fine. But when I want to merge another dictionary for filling must or should list, the empty one just disappears:

Py 3.9 style:

>>> empty_body | {'query': {'must': [{'match_phrase': {'field': 'value'}}]}}
{'aggs': {}, 'query': {'must': [{'match_phrase': {'field': 'value'}}]}}

Py 3.5 style:

>>> {**empty_body, **{'query': {'must': [{'match_phrase': {'test': 'test'}}]}}}
{'aggs': {}, 'query': {'must': [{'match_phrase': {'test': 'test'}}]}}

In both cases the should list disappears.

Is there a way to keep empty lists and KISS?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Pyrrha
  • 159
  • 2
  • 12
  • 2
    You should deep merge it Checkout the answer [here](https://stackoverflow.com/questions/7204805/how-to-merge-dictionaries-of-dictionaries/7205107#7205107) – Abdollah Keshtkar Apr 23 '21 at 09:49
  • 1
    The `|` operator only merges top-level keys. Thus it will replace the entire query value form the second list and not attempt to merge them – mousetail Apr 23 '21 at 09:52
  • you have nested dictionary - maybe it need recursion. – furas Apr 23 '21 at 09:52
  • Your code for is incorrectly formatted, could your fix the layout so we can reproduce the problem? `{'aggs': {}` has started a new dictionary – Rolv Apneseth Apr 23 '21 at 09:57
  • 1
    Though it looks like you have 2 keys called `'query'` so the query field from `empty_body` is probably getting over-ridden. What is it that you want to happen? – Rolv Apneseth Apr 23 '21 at 10:03
  • Try to merge two dictionaries into third: `>>> a = {'aggs': {}, 'query': {'bool': {'must': [], 'should': []}}}` `>>> empty_body = {}` `>>> a | empty_body` `{'aggs': {}, 'query': {'bool': {'must': [], 'should': []}}}` This is a little bit more, but work – Covx Apr 23 '21 at 11:08
  • Thanks all, it's solved with @Abdollah Keshtkar I finally use "deepmerge" package. – Pyrrha Apr 27 '21 at 14:41

0 Answers0