Python Forum

Full Version: Ordering a list of dict
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everybody,

I have a list of dictionaries i need to perform some actions on. Following the sample code:

j = json.loads(value)
#list of dict is unordered here
self.Action(j)
#list of dict is unordered here
In "self.Action" i use the following code to order the list and to assign a new field to all dictionaries:

def Action(self, pattern)
pattern = sorted(pattern, key=lambda k: k['order'])
#list of dict is ordered here
for p in pattern:
    p["new_val"] = p["order"]
When i order the list in "self.Action" it actually works out, if i print the list of dictionaries i have the right order and i have the new field ["new_val"].
The weird thing is that just after the self.Action method, the dictionaries keep the new field but they are no longer ordered in the list..
How is that possible?

Thanks
pattern is local variable for def Action. From the code provided you don't return the sorted list, so you don't change anything outside the method. However because lists are mutable, they preserve the new element added. You can use the mutability also for sorting and instead of pattern = sorted(pattern, key=lambda k: k['order']) use pattern.sort(key=lambda k: k['order'])

my_list = [{'foo':'a', 'order':3}, {'foo':'b', 'order':1}, {'foo':'c', 'order':2}]

def action(some_list):
    some_list.sort(key=lambda x: x['order'])
    for item in some_list:
        item['bar'] = None
    
action(my_list)
print(my_list)
Output:
[{'foo': 'b', 'bar': None, 'order': 1}, {'foo': 'c', 'bar': None, 'order': 2}, { 'foo': 'a', 'bar': None, 'order': 3}] >>>
Hello,

Thanks a lot, that worked. And thanks for the nice explanation :)