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:
{'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.
CodePudding user response:
textToDump = {"food": "cereal_bowl", "ingredients": []}
textToDump["ingredients"].append(
{
"milk": 100,
"cereal": 100,
}
)
textToDump["ingredients"][0].update({"honey": 10})
CodePudding user response:
textToDump = {"food": "cereal_bowl",
"ingredients":[]}
textToDump["ingredients"].append({"milk": 100,
"cereal": 100,
})
if textToDump["ingredients"]:
textToDump["ingredients"][0].update({"honey": 10})
print(textToDump)
output:
{
"food": "cereal_bowl",
"ingredients": [
{
"milk": 100,
"cereal": 100,
"honey": 10
}
]
}
CodePudding user response:
You desired output says you need a list that has only single dictionary item. So add your first dictionary like before(by .append
ing), then for the next dictionaries, you need to grab the first dictionary and update it:
textToDump["ingredients"].append({"milk": 100, "cereal": 100})
textToDump["ingredients"][0].update({"honey": 10})
However I don't think you need a list here. Why not just having a dictionary for ingredients?
textToDump = {"food": "cereal_bowl", "ingredients": {}}
textToDump["ingredients"].update({"milk": 100, "cereal": 100})
textToDump["ingredients"].update({"honey": 10})
textToDump["ingredients"]["something-else"] = 20
In case these dictionaries come separately and they are have overlapped keys, I would suggest using collections.Counter
object. You can then easily use its .update
method:
from collections import Counter
textToDump = {"food": "cereal_bowl", "ingredients": Counter()}
textToDump["ingredients"].update({"milk": 100, "cereal": 100})
textToDump["ingredients"].update({"milk": 10})
print(textToDump)