0

I am trying to build a function that sorts a list of dictionaries by one or more keys, having the list of keys passed to the function as variable (so, as a list of strings).

By following this thread, I have arranged a few lines of code that sort a list of dictionaries by their keys:

import operator
newlist = sorted( list_to_be_sorted, key=operator.itemgetter('key1','key2') )

example:

list_to_be_sorted = [
                      {'name':'Homer', 'age':39, 'height':170}, 
                      {'name':'Milhouse', 'age':10, 'height':110}, 
                      {'name':'Bart', 'age':10, 'height':112} 
                    ]

newlist = sorted( list_to_be_sorted, key=operator.itemgetter('age','name') ) # My_line

print(newlist)

[{'name': 'Bart', 'age': 10, 'height':112},
{'name': 'Milhouse', 'age': 10, 'height':110},
{'name': 'Homer', 'age': 39, 'height':170}]

Now what I want to build is a function that calls the function defined at My_line and takes as inputs:

  1. a list_to_be_sorted

  2. a list of variables, in which each variable value will be passed as argument to key=operator.itemgetter in the function at My_line

so I want that function to be defined like this:

def order_list_of_dicts_by_keys( list_to_be_sorted, keys_list ):
    pass

where, in this case, keys_list = ['age','name']

So I have run into this problem, that is:

How to pass a list of variables to a function as a "list" of arguments ?

This is what I tryed:

import operator

def order_list_of_dicts_by_keys(list_to_be_sorted, keys_strings):       
    items = tuple(keys_strings)
    sorted_list = sorted(list_to_be_sorted, key=operator.itemgetter( items )
    return sorted_list

How can I "strip" the items tuple of its parentheses, so that I can pass the correct expression to key=operator.itemgetter ?

Tms91
  • 3,456
  • 6
  • 40
  • 74
  • Duplicate: [Expanding tuples into arguments](https://stackoverflow.com/questions/1993727/expanding-tuples-into-arguments) – Nick is tired Sep 06 '21 at 16:12

1 Answers1

0

SOLVED

It is impossible to "strip" a tuple of its parentheses, but it is possible to "unpack it" with the unpacking operator (*)

So the function becomes:

import operator

def order_list_of_dicts_by_keys(list_to_be_sorted, keys_list):
    items = tuple(keys_list)
    return sorted(list_to_be_sorted, key=operator.itemgetter(*items))
Tms91
  • 3,456
  • 6
  • 40
  • 74