Sum different lists from dictionaries PYTHON -
i have data structure. list of 4 dictionaries each 4 keys , 3 values in list.
dict_list = [0] {key1: [1, 2, 3] key2: [4, 5, 6] key3: [7, 8, 9] key4: [10, 11, 12] [1] {key1: [13.......] key2: [16... etc.
i want sum each sub column [1, 4, 7, 10]....[2,5,8,11] etc. form
new_dict_list = [0] {new_key: [(1+4+7+10), (2,5,8,11), (3,6,9,12)] [1] {new_key2: [(13+16....) etc.
so i'm cascading each column within each dictionary.
i have explicit , long way far (checking math correct), there way use list comprehensions long-winded or not worth effort in end?
use zip
group [1, 4, 7, 10]....[2,5,8,11]:
>>> d = dict_list[0] >>> zip(*d.values()) [(7, 4, 1, 10), (8, 5, 2, 11), (9, 6, 3, 12)]
use map
generate new list:
>>> map(sum, zip(*d.values())) [22, 26, 30]
if using python3.x, need list(map...)
list.
Comments
Post a Comment