0

I have tried zip with a list of list and it worked.

data_list = [
   [1, 2, 3],
   [1, 3, 7],
   [5, 8, 1]
]
total = [sum(x) for x in zip(*data_list)]

total was as expected:

[7, 13, 11]

now I have dictionary

data_dict = {
   'a': [1, 2, 3],
   'b': [1, 3, 7],
   'c': [5, 8, 1]
}

and I want exact same output as mentioned above. How can I do that with data_dict?

meowgoesthedog
  • 14,670
  • 4
  • 27
  • 40
Rafiul Sabbir
  • 626
  • 6
  • 21
  • 2
    Your `data_dict` is not a valid python dictionary, but if it were you might be looking for `total = [sum(x) for x in zip(*data_dict.values())]`. **Edit**: It wasn't valid before the edit by @meowgoesthedog. – pault Feb 27 '19 at 16:58
  • 1
    Possible duplicate of [How can I get list of values from dict?](https://stackoverflow.com/questions/16228248/how-can-i-get-list-of-values-from-dict) – pault Feb 27 '19 at 16:59
  • I was trying with map(dict.items, data_dict) inside zip() but it solved my problem. Thanks a lot @pault :D – Rafiul Sabbir Feb 27 '19 at 17:02
  • 2
    Be aware of issues related to order. See related: [Are dictionaries ordered in Python 3.6+?](https://stackoverflow.com/questions/39980323/are-dictionaries-ordered-in-python-3-6/39980744) – pault Feb 27 '19 at 17:05
  • I already have an ordered dict(used collections.OrderedDict) and all the lists in this dictionary has the same len(). Thanks again for mentioning the corner case. – Rafiul Sabbir Feb 27 '19 at 17:07

1 Answers1

2
total = [sum(x) for x in zip(*data_dict.values())]

values() returns the values of the items in the dict. This gives you an Iterable of lists, which is pretty close to the first example.

Javier
  • 2,752
  • 15
  • 30