Search code examples
pythondictionarynestedassign

How to assign the values of the nested dictionary to separate variables in python?


df_dict = {
    b'A': {'lo': 31.610000610351562, 'hi': 32.25}, 
    b'AA': {'lo': 32.810001373291016, 'hi': 34.040000915527344}, 
    b'AA/PR': {'lo': 76.75, 'hi': 76.75}, 
    b'AAA': {'lo': 60.31999969482422, 'hi': 60.64820098876953}
}

for ticker in df_dict:
    print(ticker)
    for price in df_dict[ticker]:
        print(df_dict[ticker][price])

Output

A
31.6100006104
32.25
AA
32.8100013733
34.0400009155
AAA
60.3199996948
60.6482009888
AA/PR
76.75
76.75

The output of the above is: Ticker 'lo' value 'hi' value

I want to assign 'lo' and 'hi' values to two variables and calculate their ratio.

The above code is where I am at, and I am stuck there.


Solution

  • You just have to access the 'lo' and 'hi' keys and assign the values to the variables. Then you can calculate the ratio.

    for ticker in df_dict:
        lo, hi = df_dict[ticker]['lo'], df_dict[ticker]['hi']
        print('Ratio:', lo / hi)