I'm having some trouble in finding a solution to this problem. I need to compare items belonging to different keys in a dictionary. If the comparison equals my parameter, I need a third (new) element to be inserted in a new key on this very same dictionary. Below is an example of what I intend to do. Hope it makes it easier to understand:
A={"names":["jason","peter","mary"],"ages":[25,35,45],"health":["Good","Good","Poor"]}
I need to compare each value of "ages"
with each item of "health"
, respectively. If the value in "ages"
is >20 AND the value in "health"
is "Good"
, I need to add values "yes"
or "no"
to a new key "fit"
in this dictionary, according to the results of the comparisons carried out before.
I have been looking for all the possible ways to do this, but it didn't work out.
You can do it in simple way and understand if you are new to python programming. I try to help based on given scenario. @J_H answer is also right.. You can use both answers for your reference.
A={"names":["jason","peter","mary"],"ages":[25,35,45],"health":
["Good","Good","Poor"]}
dicts = {}
age = (A.get("ages"))
health = (A.get("health"))
for i, j in zip(age, health):
if i > 20 and j == "Good":
dicts.setdefault("fit", []).append("yes")
else:
dicts.setdefault("fit", []).append("no")
print(dicts)