Home > database >  Transform values in a list of dictionaries using lambda
Transform values in a list of dictionaries using lambda

Time:03-01

I have a list of dictionaries, like so:

matrices = [
    { "name": 'dark_matter_and_gas', 'matrix': dark_matter_a_matrix},
    { "name": 'dark_matter_and_gas', 'matrix': dark_matter_b_matrix},
    { "name": 'dark_matter_and_gas', 'matrix': dark_matter_c_matrix},
    { "name": 'dark_matter_and_gas', 'matrix': dark_matter_d_matrix},
    { "name": 'dark_matter_and_gas', 'matrix': dark_matter_e_matrix},
]

Where each 'matrix' value is a pandas matrix object, and dark_matter_a_matrix.dtypes, for instance, returns a series of floats, for each matrix.


Now I'd like to do some transformation to all matrices in the dictionary, in one line.

The transformation would apply some function(matrix) to all dict values at once.

In pandas I would use apply() with lambda in a DataFrame, like so:

new_matrices = matrices['matrix'].apply(lambda x: function(x))

Which is the best way to this to the dictionary? I must keep the dictionary with the same structure.

CodePudding user response:

You could iterate over the dictionaries in matrices and apply function to each of the DataFrames in each dictionary:

for d in matrices:
    d['matrix'] = d['matrix'].apply(lambda x: function(x))

I guess you could write it as a list comprehension as well:

matrices = [{'name': 'dark_matter_and_gas', 'matrix': d['matrix'].apply(lambda x: function(x))} for d in matrices]

but it's a lot less efficient in this case since you can modify each dictionary in loop without creating a new list.

  • Related