python - Subtract values from list of dictionaries from another list of dictionaries -
i have 2 lists of dictionaries.
foo = [{'tom': 8.2}, {'bob': 16.7}, {'mike': 11.6}] bar = [{'tom': 4.2}, {'bob': 6.7}, {'mike': 10.2}]
the subtraction of , b should updated in foo:
foo = [{'tom': 4.0}, {'bob': 10.0}, {'mike': 1.4}]
now tried 2 loops , zip
-function:
def sub(a,b): mydict,mydictcorr in zip(a,b): {k:[x-y x, y in mydict[k], mydictcorr[k]] k in mydict} return mydict print sub(foo,bar)
i typeerror: 'float' object not iterable
. where's mistake?
you close. issue list comprehension had in dictionary comprehension. mydict[k], mydictcorr[k]
both returning floats, trying iterate on them [x-y x, y in mydict[k], mydictcorr[k]]
.
this work you:
def sub(base, subtract): corrected = [] base_dict, sub_dict in zip(base, subtract): corrected.append({k: v - sub_dict.get(k, 0) k, v in base_dict.items()}) return corrected
or less readable one-liner (because wanted see if could):
def sub(base, subtract): return [{k: v - sub_dict.get(k, 0) k, v in base_dict.items()} base_dict, sub_dict in zip(base, subtract)]
having said that, may still see weird results when subtract floats. eg, {'tom': 3.999999999999999}
. may want wrap v - sub_dict.get(k, 0)
in call round.
Comments
Post a Comment