Python nested loops inside dict

Python nested loops inside dict

Problem Description:

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:

DatesCurrencyRate
2022-11-30EUR123
2022-12-01EUR122
2022-12-02EUR123
2022-12-03EUR124
2022-12-04EUR122
2022-12-05EUR121
2022-12-06EUR123

Solution – 1

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

Solution – 2

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"])
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject