Search code examples
pythontupleslist-comprehensionargsiterable-unpacking

Creating a tuple out of *args


I've tried, but I can't figure this out so far. I want to create a list of tuples, each one built out of dictionary values:

my_list = [(x['field1'], x['field2']) for x in my_dict]

But the issue is that I want to do this inside a function, passing the fields I want to get to *args:

my_func('field1', 'field2')

How can I build the first list comprehension out of the *args list?

Thanks!

I'll try to clarify:

Briefly, what I want to do is map this:

my_func('field1', 'field2')

To this:

tuple(x['field1'], x['field2'])

Which will be a statement inside my_func(*args)


Solution

  • You can create a tuple by doing another comprehension over the args:

    def my_func(*args):
        return [tuple(x[arg] for arg in args) for x in my_dict]
    

    However this assumes that your my_dict is a global variable. But now you can call it like you specified with my_func('field1', 'field2').

    I would advise to add the dictionary to the function definition:

    def my_func(my_dict, *args):
        return [tuple(x[arg] for arg in args) for x in my_dict]
    

    and call it as my_func(my_dict, 'field1', 'field2')