Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Appending list of key:value pairs without adding more curly braces in Python

I need to append a list of key:value pairs multiple times. However, this produces additional curly braces after each .append().

Basically, I have something like this:

textToDump = {"food": "cereal_bowl",
                      "ingredients":[]}
    
textToDump["ingredients"].append({"milk": 100,
                                 "cereal": 100,
                                 })
textToDump["ingredients"].append({"honey": 10})
print(textToDump)

which results in:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'food': 'cereal_bowl', 'ingredients': [{'milk': 100, 'cereal': 100}, {'honey': 10}]}

what I need is:

{'food': 'cereal_bowl', 'ingredients': [{'milk': 100, 'cereal': 100, 'honey': 10]}

I also tried using dictionary+.update() instead of list. However, I need to be able to have duplicate entries in my structure ("ingredients"). What would be the simplest way of achieving this?

Thanks in advance.

>Solution :

textToDump = {"food": "cereal_bowl", "ingredients": []}

textToDump["ingredients"].append(
    {
        "milk": 100,
        "cereal": 100,
    }
)
textToDump["ingredients"][0].update({"honey": 10})

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading