0

Let's say I have a list of dictionnaries call x. If I want to extract the keys and push them into a new list called y :

y = {k for d in x for k in d.keys()}
y = {k for k in chain(*x)}

Now I want to do the same operation with a function. As I don't know the name of the list of dict in advance, I was thinking of using *args

def formatting(*args):    
    return {k for d in args for k in d.keys()}

x_list = formatting(x)

But doing this return AttributeError: 'list' object has no attribute 'keys'

When I passing the real variable name in the function, it's working...

What is the correct way of passing list of dict into a function ?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Neuhneuh
  • 11
  • 4

2 Answers2

1
x_list = formatting(*x)  # <-- don't forget to expand "x" into "args"

Otherwise args = (x,) rather than args = x like you're expecting.

scnerd
  • 5,836
  • 2
  • 21
  • 36
0

First of all you should use the List Comprehension in order for y become a list

y = [k for d in x for k in d.keys()]

After, the way scnerd commented here, you should expand X in Args before using it in the function. However I didn't get why you're using the *args, since even if you don't know the name of the dicts list, you could use the function name normally and have your code working with:

def formatting(dicts_list):    
    return [k for d in dicts_list for k in d.keys()]

x_list = formatting(x)
Luan Naufal
  • 1,346
  • 9
  • 15
  • Because I have multiple list of dict to be passed in the function and each one should return a different function. – Neuhneuh Nov 13 '18 at 20:17