-2

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)

Ivan
  • 51
  • 9
  • 1
    Not so clear what you want to do. Can you give an example (or two) with the input/output you want? – Dekel Dec 07 '16 at 23:24
  • Unclear ... what is `my_dict` in this ... a list of dictionaries? Are you wanting to get a different field from each element of `my_dict`? – donkopotamus Dec 07 '16 at 23:25
  • Like what exactly are you asking? Creating tuples from function arguments? So you want function which will return tuple ? – pagep Dec 07 '16 at 23:25
  • `*args` **already creates a tuple** - `args`, inside the function, would be `('field1', 'field2')` – jonrsharpe Dec 07 '16 at 23:31

2 Answers2

1

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')

MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • It's ok, in fact the function is more complex, and includes the dictionary. I made it simpler so the question is clearer. Thanks again! – Ivan Dec 07 '16 at 23:43
0

Simply refer to those arguments as normal:

def f(d, a, b):
    return [(x[a], x[b]) for x in d]

result = f(my_dict, 'field1', 'field2')
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97