Hello, I am using the FQL merge function, and as per my understanding two objects (in my case, Python dictionaries) should merge in sequential order when there are no key conflicts:
result = client.query(
q.merge(
{"a": "Apple", "b": "Banana"},
{"x": "width", "y": "height"}
)
)
print(result)
{'a': 'Apple', 'b': 'Banana', 'x': 'width', 'y': 'height'}
(from [Merge :: Fauna Documentation])
However when I merge the following two dicts they come out with the keys mixed up - the mixed up keys are always inserted in the same (non-sequential) order:
dict1 = {'keyA': 'a', 'keyB': 'b', 'keyC': 'c', 'keyD': d}
dict2 = {'keyE': 'e'}
q.create(q.collection(collection), {'data': q.merge(dict1, dict2)})
result = {'keyB': 'b', 'keyE': 'e', 'keyC': 'c', 'keyA': a, 'keyD': d}
Is there any way to ensure the object merging happens in some kind of sequential order?
Or is this perhaps a bug?
Thanks for your help.
Hi @stjornkerfi,
Python dictionaries are unsorted by design. If you want to sort a dictionary you should use the OrderedDict
class to do so.
Since the underlying dictionary itself is unsorted there’s no way for the Python driver to natively insert or read the resulting object in any kind of sorted way. It just takes the keys and values that are supplied to it then runs the merge. I haven’t tried it but I suspect if you used the OrderedDict
as the object the merge would happen as you expect it to.
Cory
Hi @stjornkerfi,
So we did some further digging and it looks like you may have indeed found a bug in how merging operates. Our engineers are working on a solution now.
Thank you for bringing this to our attention.
Hi Cory,
Thanks for the update and good to hear the solution is already being worked on.
I am using Python 3.9 so the dictionaries should be sorted by default.
The new API includes an Object.assign
method, which works as expected. At this time, the v4 Merge
function still may reorder keys in an undefined way. If key order is important to you within FQL, then we recommend migrating to the v10 API.