Home > other >  How can I work with the dictionary in the dictionary?
How can I work with the dictionary in the dictionary?

Time:08-25

I have defined the standard deviation limits for different columns in a dataframe. I did this by defining a function. The output is a dictionary, which always consists of two values. Now how can I explicitly use a certain value in the dictionary which is in a dictionary?

here is my Code:

def Sigma_limit(df, col, x):
    plus_std_dev  = ((df[col].mean())   (x*df[col].std()))
    minus_std_dev = ((df[col].mean()) - (x*df[col].std()))
    return {' 3Sigma_limited': plus_std_dev,
            '-3Sigma_limited': minus_std_dev}

Sigma_limits = {'A2_3Sigma': Sigma_limit(A_df, 'A2_column', 3),
                'A3_3Sigma': Sigma_limit(A_df, 'A3_column', 3),
                'A4_3Sigma': Sigma_limit(A_df, 'A4_column', 3),
                'A5_3Sigma': Sigma_limit(A_df, 'A5_column', 3)}

enter code here

so I have a dictionary with 4x2 dictionaries each and now I would like to use them all separately

CodePudding user response:

I have managed to print out the data you need:

import pandas as pd

A_df = pd.DataFrame({'A2_column': [1,2,3,4],
                     'A3_column': [6,1,3,4],
                     'A4_column': [7,2,8,5],
                     'A5_column': [2,2,2,4]})

def Sigma_limit(df, col, x):
    plus_std_dev  = ((df[col].mean())   (x*df[col].std()))
    minus_std_dev = ((df[col].mean()) - (x*df[col].std()))
    return {' 3Sigma_limited': plus_std_dev,
            '-3Sigma_limited': minus_std_dev}

Sigma_limits = {'A2_3Sigma': Sigma_limit(A_df, 'A2_column', 3),
                'A3_3Sigma': Sigma_limit(A_df, 'A3_column', 3),
                'A4_3Sigma': Sigma_limit(A_df, 'A4_column', 3),
                'A5_3Sigma': Sigma_limit(A_df, 'A5_column', 3)}

for col in A_df.columns:
    k = col[0:2] '_3Sigma'    #to get key A2_3Sigma, A3_3Sigma, etc
    print(f"{col} ranges between {Sigma_limits[k]['-3Sigma_limited']} and {Sigma_limits[k][' 3Sigma_limited']}")

Output:

A2_column ranges between -1.372983346207417 and 6.372983346207417
A3_column ranges between -2.7449979983983983 and 9.744997998398398
A4_column ranges between -2.437253933193772 and 13.437253933193773
A5_column ranges between -0.5 and 5.5

A simpler way is to return a list (instead of dictionary), same output!

def Sigma_limit(df, col, x):
    plus_std_dev  = ((df[col].mean())   (x*df[col].std()))
    minus_std_dev = ((df[col].mean()) - (x*df[col].std()))
    return [minus_std_dev, plus_std_dev]

for col in A_df.columns:
    k = col[0:2] '_3Sigma'    #to get key A2_3Sigma, A3_3Sigma, etc
    print(f"{col} ranges between {Sigma_limits[k][0]} and {Sigma_limits[k][1]}")

CodePudding user response:

One way is to assign another variable:

d = Sigma_limits['A2_3Sigma']

Now you just have another dictionary that you use in the same way as any dictionary. There is nothing special when nesting dictionaries. Just use indexing.

  • Related