Home > Back-end >  Python nested loops inside dict
Python nested loops inside dict

Time:12-07

I have a dict exchange rates. It has 3 levels: rates, date and currency.

"rates": {
        "2022-11-30": {
            "AED": 0.06019,
            "AFN": 1.442036,
            "ALL": 1.836137,
            "AMD": 6.464451,
            "ANG": 0.029525,
            "AOA": 8.304432,
            "ARS": 2.741601,
            ................
            etc.

I want to write a loop that first will capture the date in a variable i, for example "2022-11-30", after go doown, take the desired currency "EUR" and from this will get the rate.

for i in r_dict["rates"]:
    for y in r_dict["rates"][i]:
        for e in r_dict["rates"][i][y]:
            print(e)

There info from 2022-11-30 to 2022-12-06 and desired output should look like this:

Dates Currency Rate
2022-11-30 EUR 123
2022-12-01 EUR 122
2022-12-02 EUR 123
2022-12-03 EUR 124
2022-12-04 EUR 122
2022-12-05 EUR 121
2022-12-06 EUR 123

CodePudding user response:

My answer is very similar to Andrej's but I show how to build your output as a python-native matrix (i.e. list of lists) as well as a pandas dataframe.

nested = {
    "rates": {
        "2022-11-30": {
            "AED": 0.06019,
            "AFN": 1.442036,
            "ALL": 1.836137,
            "AMD": 6.464451,
            "ANG": 0.029525,
            "AOA": 8.304432,
            "ARS": 2.741601,
        }
    }
}

# Verbose implementation
tabular = []

for dt, stocks in nested["rates"].items():
    for currency, rate in stocks.items():
        tabular.append([dt, currency, rate])

# Concise implementation
tabular = [
    [dt, currency, rate]
    for dt, stocks in nested["rates"].items()
    for currency, rate in stocks.items()
]

# Convert to pandas
import pandas as pd

df = pd.DataFrame(tabular, columns=["date", "currency", "rate"])

CodePudding user response:

To create a desired dataframe you can use next example:

import pandas as pd

data = {
    "rates": {
        "2022-11-30": {
            "AED": 0.06019,
            "AFN": 1.442036,
            "EUR": 100,
        },
        "2022-12-01": {
            "AED": 0.06019,
            "AFN": 1.442036,
            "EUR": 101,
        },
        "2022-12-02": {
            "AED": 0.06019,
            "AFN": 1.442036,
            "EUR": 102,
        },
    }
}

df = pd.DataFrame(
    [(k, "EUR", v.get("EUR")) for k, v in data["rates"].items()],
    columns=["Dates", "Currency", "Rate"],
)
print(df)

Prints:

        Dates Currency  Rate
0  2022-11-30      EUR   100
1  2022-12-01      EUR   101
2  2022-12-02      EUR   102
  • Related