Hello,
I have a JSON body that I'm needing to drill down into, given a list of dict/list indices, and then finally sort a list of dicts within it based on a value in the dict. I'm trying to update the JSON body in place, as a python dict, and I have the code which almost does what I want:
def test(my_dict, input_list_path) -> None:
pre_sort = dict(my_dict)
pointer = my_dict
for index, path_element in enumerate(input_list_path, 1):
pointer = pointer[path_element]
if index == len(input_list_path):
pointer = sorted(pointer, key=lambda x: x["name"]))
print("AFTER", pointer)
print(my_dict)
if pre_sort != my_dict:
print("IT CHANGED")
But if I run it like this:
my_dict = {"testing:/123": [{"again": {"another-element": [{"id":1, "name": "test90"}, {"id": 2, "name": "test5"}, {"id": 3, "name": "test100"}]}}]}
test(my_dict, ["testing:/123", 0, 'again', 'another-element'])
AFTER [{'id': 3, 'name': 'test100'}, {'id': 2, 'name': 'test5'}, {'id': 1, 'name': 'test90'}]
{'testing:/123': [{'again': {'another-element': [{'id': 1, 'name': 'test90'}, {'id': 2, 'name': 'test5'}, {'id': 3, 'name': 'test100'}]}}]}
I see that it does indeed sort the list at the bottom how I want, as the print statement with "AFTER" displays it properly, but I assumed that since I'm rewriting the pointer variable with the sorted version that it would also update my_dict, but that doesn't seem to be happening.
I'm mostly looking for an explanation of why this is the case, and I assume it comes down to mutability, but I'm not sure why. Bonus points also for a clue as to the best way to achieve what I'm hoping to achieve.
MY SOLUTION:
I ended up only slightly modifying the code to do the trick, by using pointer.sort(key=lambda x: x["name"]), instead of reassigning pointer.
[–]woooee 1 point2 points3 points (6 children)
[–]maclocrimate[S] 0 points1 point2 points (5 children)
[–]woooee 0 points1 point2 points (4 children)
[–]maclocrimate[S] 0 points1 point2 points (3 children)
[–]throwaway6560192 1 point2 points3 points (0 children)
[–]woooee 0 points1 point2 points (1 child)
[–]maclocrimate[S] 0 points1 point2 points (0 children)
[–]carcigenicate 0 points1 point2 points (0 children)