Search code examples
python-3.xloopsdictionaryfor-loopnested

Iterate over a nested dictionary format and save the output result


I was looking but didn´t found something regarding iterate over one nested dictionary and save the output.

This is the dictionary:

 dictionary={
    "A": "EXAMPLE",
    "comment": "This is an example",
    "author": "JKROWLING",
    "book1": [
        {
            "book_name": 'place book name',
            "amount_pages":'place book_pages' 
        }
    ]
}

Now I have a df with the following information:

data = {'book_name': ['philosopher', 'chamber', 'azkaban', 'goblet', 'phoenix','prince','hallow'],
        'amount_page': [220, 280, 330, 450, 1000,650,600]
        }

df = pd.DataFrame(data)

print(df)

I don´t know how to iterate a dataframe or a list in a dictionary and save the results. I mean, the expected ouput is to get all the book_name and amount of pages in different dictionaries. The expected output would be


{
    "A": "EXAMPLE",
    "comment": "This is an example",
    "author": "JKROWLING",
    "book1": [
        {
            "book_name": 'philosopher',
            "amount_pages":220 
        }
    ]
}

 dictionary={
    "A": "EXAMPLE",
    "comment": "This is an example",
    "author": "JKROWLING",
    "book1": [
        {
            "book_name": 'Chamber',
            "amount_pages":280
        }
    ]
}

 dictionary={
    "A": "EXAMPLE",
    "comment": "This is an example",
    "author": "JKROWLING",
    "book1": [
        {
            "book_name": 'Azkaban',
            "amount_pages":330
        }
    ]
}

Until the end of the dataframe.... I need all the values in different dictionaries


Solution

  • You can use zip() + for-loop to get names/pages from the dataframe and store the dictionaries in the list:

    out = []
    for n, p in zip(df["book_name"], df["amount_page"]):
        dictionary = {
            "A": "EXAMPLE",
            "comment": "This is an example",
            "author": "JKROWLING",
            "book1": [{"book_name": n, "amount_pages": p}],
        }
        out.append(dictionary)
    
    print(out)
    

    Prints:

    [
        {
            "A": "EXAMPLE",
            "comment": "This is an example",
            "author": "JKROWLING",
            "book1": [{"book_name": "philosopher", "amount_pages": 220}],
        },
        {
            "A": "EXAMPLE",
            "comment": "This is an example",
            "author": "JKROWLING",
            "book1": [{"book_name": "chamber", "amount_pages": 280}],
        },
        {
            "A": "EXAMPLE",
            "comment": "This is an example",
            "author": "JKROWLING",
            "book1": [{"book_name": "azkaban", "amount_pages": 330}],
        },
    
    ...